Asp.net MVC中 Controller 与 View之间的数据传递

在ASP.NET MVC中,常常会在Controller与View之间传递数据ajax

一、Controller向View中传递数据spa

(1)使用ViewData["user"]code

(2)使用ViewBag.userorm

(3)使用TempData["user"]对象

(4)使用Model(强类型)blog

区别:input

(1)ViewData与TempData方式是弱类型的方式传递数据,而使用Model传递数据是强类型的方式。string

(2)ViewData与TempData是彻底不一样的数据类型,ViewData数据类型是ViewDataDictionary类的实例化对象,而TempData的数据类型是TempDataDictionary类的实例化对象。it

(3)TempData实际上保存在Session中,控制器每次请求时都会从Session中获取TempData数据并删除该Session。TempData数据只能在控制器中传递一次,其中的每一个元素也只能被访问一次,访问以后会被自动删除。io

(4)ViewData只能在一个Action方法中进行设置,在相关的视图页面读取,只对当前视图有效。理论上,TempData应该能够在一个Action中设置,多个页面读取。可是,实际上TempData中的元素被访问一次之后就会被删除。

(5)ViewBag和ViewData的区别:ViewBag 再也不是字典的键值对结构,而是 dynamic 动态类型,它会在程序运行的时候动态解析。

二、View向Controller传递数据

在ASP.NET MVC中,将View中的数据传递到控制器中,主要经过发送表单的方式来实现。具体的方式有:

(1)经过Request.Form读取表单数据

View层:

@using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post))
{
    @Html.TextBox("Name");
    @Html.TextBox("Text");
    <input type="submit" value="提交" />
}

Controller:

     [HttpPost]
        public ActionResult HelloModelTest()
        {
            string name= Request.Form["Name"];
            string text= Request.Form["Text"];
            return View();
        }

(2)经过FormCollection读取表单数据

[HttpPost]
        public ActionResult HelloModelTest(FormCollection fc)
        {
            string name= fc["Name"];
            string text  = fc["Text"];
            return View();
        }

(3)经过模型绑定

  1)、将页面的model直接引过来

[HttpPost]
public ActionResult HelloModelTest( HelloModel model)
{
    // ...
}

  2)、页面的元素要有name属性等于 name和text 的

 public ActionResult HelloModelTest( string name,string text)
{
    // ….
}

(4)经过ajax方式,可是里面传递的参数要和Controller里面的参数名称一致

相关文章
相关标签/搜索