MVC中Controller与View当中的数据传递的常用方法

MVC中Controller与View中间的数据传递的常用方法

这几天正在学习MVC,顺便就将自己每天的学习心得记录下来与大家分享一下吧!

在MVC中,Controller与View之间传递数据是很频繁的事情,所以在这里就总结一下我自己在学习中使用的几种常用的方法:

 

将数据从Controller中传递到View中:

ViewData:它是Key/Value字典集合

赋值方式(cs文件中):

ViewData["Demo"]="Hello world!";

使用方法(aspx文件中):

  <h1>
            <%:ViewData["demo"] %>
  </h1>

 

将数据从View中传递到Controller中:

方法一:使用FormCollection类型参数获取数据

 public ActionResult Index(FormCollection collection)
 {
    string str = collection["demo"];    //str="hello world!"
       return View();
 }

方法二:使用Request[key]获取数据

 public ActionResult Index()
 {
  string str = Request["demo"];    //str="hello world!"
    return View();
 }