asp.net MVC 传值

asp.net MVC传值通常指Controller和view之间的数据传递,简单总结一下:

1.ViewData

从Controller到view的值传递:

在Controller中声明一个存储数据的键值对,

代码清单1

public ActionResult Index()
{
     ViewData["names"] = "张三";
     ViewData["othername"] = "李四";
     return View("BookatmIndex");
}

在view中使用,

代码清单2

显示方法一:控件只有一个参数,直接把控件名作为查找值的键。

<body> <div> <%Html.BeginForm("DoIndex", "Bookatm", FormMethod.Post); %> 请输入一个名字: <%=Html.TextBox("Names") %><br /> 请输入另一个名字: <%=Html.TextBox("OtherName") %><br /> <input id="subbutton" type="submit" value="发布" /> <%Html.EndForm(); %> </div> </body>
显示方法二:控件有两个参数,把值保存在其他变量中,控件第二个参数为控件显示内容。

<body> <%string name=ViewData["Name"] as string; %> <%string othername = ViewData["OtherName"] as string; %> <div> <%Html.BeginForm("DoIndex", "Bookatm", FormMethod.Post); %> 请输入一个名字: <%=Html.TextBox("Names",name) %><br /> 请输入另一个名字: <%=Html.TextBox("OtherName",othername) %><br /> <input id="subbutton" type="submit" value="发布" /> <%Html.EndForm(); %> </div> </body>

显示结果,

从view到Controller的值传递:

代码清单3

把从表单获取的值再保存在新的键值对中:此方法的调用在代码清单2表单中<%Html.BeginForm("DoIndex", "Bookatm", FormMethod.Post); %>
public ActionResult DoIndex()
{
      ViewData["NewName"] = Request.Form["Name"];
      ViewData["NewOtherName"] = Request.Form["OtherName"];
      return View("AddBookatm");
}

 2.TempData

ASP.NET MVC的TempData用于传输一些临时的数据,例如在各个控制器Action间传递临时的数据或者给View传递一些临时的数据。TempData默认是使用Session来存储临时数据的,TempData中存放的数据只一次访问中有效,一次访问完后就会删除了的。这个一次访问指的是一个请求到下一个请求,因为在下一个请求到来之后,会从Session中取出保存在里面的TempData数据并赋值给TempData,然后将数据从Session中删除。

代码清单4

public ActionResult Index()
{
        ViewData["names"] = "我使用的是ViewData";
        TempData["Messages"] = "我使用的是TempData";
        return RedirectToAction("DoIndex");  //调用DoIndex方法
}
public ActionResult DoIndex()//此方法使用其他控制器,并打开页面
{
        return RedirectToAction("Index", "Home");
}

代码清单5:

<body>
    <div>
    ViewData:<%=ViewData["names"]%><br />
    TempData:<%=TempData["Messages"]%>
    </div>
</body>

结果:

小结:TempData是可以跨action传值的。而ViewData和ViewBag不能跨action。

3.ViewBag

ViewBag 不再是字典的键值对结构,而是 dynamic 动态类型,它会在程序运行的时候动态解析。

代码清单6

public ActionResult Index()
{
        ViewBag.Message_ViewBag = "我使用的是ViewBag";
        ViewData["names"] = "我使用的是ViewData";
        TempData["Messages"] = "我使用的是TempData";
        return View("BookatmIndex");
}

代码清单7

<body>
    <div>
        <%Html.BeginForm("DoIndex", "Bookatm", FormMethod.Post); %>
        ViewBag:<%=ViewBag.Message_ViewBag%><br />
        ViewData:<%=ViewData["Names"]%><br />
        TempData:<%=TempData["Messages"]%><br />
        <input id="subbutton" type="submit" value="发布" />
        <%Html.EndForm(); %>
    </div>
</body>

结果:

原文地址:https://www.cnblogs.com/yxys/p/5180218.html