在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") %>
<form name="form1" action="/Home/Index" method="post"> Name:<input type="text" name="name" /><br /> Sex: <input type="text" name="sex" /> <input type="submit" value="submit" /> </form> <% 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(); }
2).利用Request.From或Request.QueryString
public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; ViewData["name"] = Request.Form["name"]; ViewData["sex"] = Request.Form["sex"]; return View(); }
3). 利用FormCollection获取页面值
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); }
<p> <%User u = (User)ViewData.Model;%> UserName: <%= Html.Encode(u.UserName) %> </p> <p> Password: <%= Html.Encode(u.Password) %> </p>