MVC Controller 与 View 传值
Controller 到 View
1 强类型
控制器
// GET: /Test/ public ActionResult Index() { DateTime date = DateTime.Now; //大部分时候使用自定义类型 return View(date); }
视图
@model DateTime @{ ViewBag.Title = "Index"; } <h2>Index</h2> <h2>The time is: @Model.ToString("yyyy年MM月dd日 HH:mm:ss");</h2> <h2>The day is: @(((DateTime)Model).DayOfWeek) </h2> <h2>The day is: @Html.TextBoxFor(m=>m.DayOfYear)</h2>
2 ViewBag,ViewData,TempData
控制器(注意第二项,第三项输出结果)
public ActionResult TempDataTest() { TempData["Message"] = "TempData Message"; ViewData["Message"] = "ViewData Message"; ViewBag.Mesaage = "ViewBag Message"; ViewBag.Info = "ViewBag Message"; return View(); }
视图
@{ ViewBag.Title = "TempDataTest"; } <h2>TempDataTest</h2> <h2>@TempData["Message"]</h2> <h2>@ViewData["Message"]</h2> <h2>@ViewBag.Message</h2> <h2>@ViewBag.Info</h2>
View 到 Controller
1 QueryString
视图
@{ ViewBag.Title = "QueryStringTest"; } <h2>@ViewData["Message"]</h2> <h2>QueryStringTest</h2> <h2> @Html.ActionLink("TestController", "QueryStringTest", new { word = "word" }) </h2>
控制器
public ActionResult QueryStringTest(string Word) { ViewData["Message"] = Request.QueryString["Word"]; ViewData["Message1"] = Word; return View(); }
2 Post
视图
@{ ViewBag.Title = "PostTest"; } <h2>PostTest</h2> <h2>@TempData["Message"]</h2> <div> //第一种
<form action="/Test/PostTest" method="post"> <ul> <li>用户名:<input type="text" value="" name="UserName" /></li> <li>密 码:<input type="text" value="" name="Password" /></li> </ul> <input type="submit" value="提交" /> </form>
//第二种 @using (Html.BeginForm("PostTest", "Test", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <p> <div class="form-group"> @Html.Label("用户名", new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBox("username", "", new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.Label("密码", new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBox("Password", "", new { @class = "form-control" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="提交" class="btn btn-default" /> </div> </div> </p> } </div>
控制器
public ActionResult PostTest() { return View(); } [HttpPost] public ActionResult PostTest(string UserName, string Password) { TempData["Message"]= "username ="+UserName +" Password="+Password; return View(); }