在asp.net2.0的网页开发模式下,我们一般通过直将访问页面控件, 将值写入到页面, 但在Asp.net MVC模式下,已不能在Controller中再去访问页面控件了,要如何才能给View页面传值呢?在Controller中有两个字典(ViewData和TempData)来实现View之间的值传递,Controller通过ViewData,TempData传通到ViewResult中, 然后再由ViewResult传递到ViewPage中来实现值传递的。
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
Name:<%= Html.TextBox("name") %>
<%
if (ViewData["name"] != null)
{
Response.Write("your name is:" + ViewData["name"] + ", your sex is:" + ViewData["sex"]);
}
%>
:
public ActionResult Index(string name, string sex)
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData["name"] = name;
ViewData["sex"] = sex;
return View();
}
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData["name"] = Request.Form["name"];
ViewData["sex"] = Request.Form["sex"];
return View();
}
public ActionResult Index(FormCollection form)
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
User u=new User();
u.Name = form["Name"];
u.Password = form["Password"];
return View(u);
}
public ActionResult ModelDemo()
{
User u= new User() { UserName="li", Password="abcde" };
return View(u);
}
<%User u = (User)ViewData.Model;%>
UserName:
<%= Html.Encode(u.UserName) %>
Password:
<%= Html.Encode(u.Password) %>