码迷,mamicode.com
首页 > 其他好文 > 详细

Controller与View之间的数据传递

时间:2015-09-16 17:28:25      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

1)Controller向View传递数据
ViewData["message"] = "Hello";//使用ViewData传递数据
ViewBag.Time = DateTime.Now;//ViewBag传递数据
TempData["mes"] = "text";//使用TempData传递数据
//使用静态字段定义变量
public static string str;//全局的
str = "123";
//使用静态集合定义变量
public static List<string> list = new List<string>();//全局的,必须new出来一个对象或者new List<string>();写在方法里面,否则会出现“未将对象引用设置到对象的实例”的错误
list.RemoveRange(0,list.Count);//添加前先清除集合所有元素
list.AddRange(new string[] { "aaa", "bbb", "ccc" });
使用Model传递数据:
使用Model传递数据的时候,通常在创建View的时候我们会选择创建强类型View
View访问Controller数据:
<h1>@ViewData["message"]</h1>
<h2>@ViewBag.Time</h2>
<h3>@TempData["mes"]</h3>
@using MVCStart.Controllers //调用静态字段时,需要引用该方法所在的命名空间
<h4>@LoginController.str</h4> //用类名.调用

总结:
1.ViewData与TempData方式是弱类型的方式传递数据,而使用Model传递数据是强类型的方式。
2.ViewData与TempData是完全不同的数据类型,ViewData数据类型是ViewDataDictionary类的实例化对象,而TempData的数据类型是TempDataDictionary类的实例化对象。
3.TempData实际上保存在Session中,控制器每次执行请求时都会从Session中获取TempData数据并删除该Session。TempData数据只能在控制器中传递一次,其中的每个元素也只能被访问一次,访问之后会被自动删除。
4.ViewData只能在一个Action方法中进行设置,在相关的视图页面读取,只对当前视图有效。理论上,TempData应该可以在一个Action中设置,多个页面读取。但是,实际上TempData中的元素被访问一次以后就会被删除。
5.使用静态集合定义全局变量时,new出来的对象不要写在方法外面,应写在方法里面,否则每次在View获取到的集合数据会累加一次;

2)View向Controller传递数据
通过表单form传递数据,此为post请求获取
定义标签name属性:
<input type="text" name="txtname" />
通过Request.Form[""]获取View数据
string username = Request.Form["txtname"];
通过public ActionResult Login(FormCollection form)获取View数据
string username = form["username"];
//get请求获取
string username = Request.QueryString["username"];

Controller与View之间的数据传递

标签:

原文地址:http://www.cnblogs.com/genesis/p/4813547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!