实例一:首先简单显示实例:
控制器代码:
public class WujyTestController : Controller { public ActionResult Index() { List<UserInfo> list = new List<UserInfo>() { new UserInfo(){ Name="wujy", PassWord="123456", Age=27, BrithDay=DateTime.Now, Sex=true}, new UserInfo(){Name="zyb", PassWord="347586", Age=23, BrithDay=DateTime.Now, Sex=false} }; return View(list); } }
视图显示如下:
@model IEnumerable<FirstMvcTest.Models.UserInfo> @{ ViewBag.Title = "Index"; } <h2>Index</h2> @foreach (var item in Model) { <h1> 姓名:@item.Name 年龄:@item.BrithDay 性别:@(item.Sex?"男生":"女生") </h1> }
实例二:表单的简单运用
控制器代码:
public ActionResult TestSearch() { return View(); } public ActionResult Search(string Name) { UserInfo model=new UserInfo(); List<UserInfo> list = new List<UserInfo>() { new UserInfo(){ Name="ybs", PassWord="123456", Age=27, BrithDay=DateTime.Now, Sex=true}, new UserInfo(){ Name="wujy", PassWord="123456", Age=27, BrithDay=DateTime.Now, Sex=true}, new UserInfo(){Name="zyb", PassWord="347586", Age=23, BrithDay=DateTime.Now, Sex=false} }; if (!string.IsNullOrEmpty(Name)) { model = list.Find(u => u.Name.Contains(Name)); } return View(model); }
提交视图显示:
@{ ViewBag.Title = "TestSearch"; } @using (Html.BeginForm("Search", "WujyTest", FormMethod.Get)) { @Html.TextBox("Name", "wujy") <input type="submit" value="提交"/> }
结果显示视图:
@model FirstMvcTest.Models.UserInfo @{ ViewBag.Title = "Search"; } <h1>符合要求:</h1> @if (Model != null) { @Model.Name }
注意:BeginForm运用
@using (Html.BeginForm("Search", "WujyTest", FormMethod.Get, new { target="_blank",@class="editForm",data_validatable=true})) { @Html.Label("搜索的姓名:") @Html.TextBox("Name", "wujy") <input type="submit" value="提交"/> } 生成为: <form action="/WujyTest/Search" class="editForm" data-validatable="True" method="get" target="_blank"> <input id="Name" name="Name" type="text" value="wujy" /> <input type="submit" value="提交"/> </form>
其中data-validatable="True" 在C#符号-连字符的属性名是无效的,所以辅助方法在渲HTML时会将属性名中的下划线转换为连字符;