日期:2014-05-16 浏览次数:20891 次
首先做准备工作,为了读者方便阅读,笔者把上篇文章中(Asp.Net MVC4系列—进阶篇之Helper(1)) 的代码再复制在这边一份,这篇文章都以此为开始:
Person类(Model中):
public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Address HomeAddress { get; set; } public bool IsApproved { get; set; } public Role Role { get; set; } }
public class Address { public string Line1 { get; set; } public string Line2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string Country { get; set; } } public enum Role { Admin, User, Guest }
PersonController.cs
public class PersonController : Controller { public ActionResult CreatePerson() { return View(new Person()); } [HttpPost] public ActionResult CreatePerson(Person person) { return View(person); } }
Route:
routes.MapRoute( name: "FormRoute", url:"app/forms/{controller}/{action}" ); }
View(CreatePerson.cshtml)
<html> @modelMVCHelperStudy.Models.Person @{ ViewBag.Title = "CreatePerson"; } <h2>CreatePerson</h2> <body> @using(Html.BeginRouteForm("FormRoute", new {},FormMethod.Post, new { @class ="personClass", data_formType="person"})) { <div class="dataElem"> <label>PersonId</label> @Html.TextBoxFor(m =>m.PersonId) </div> <div class="dataElem"> <label>FirstName</label> @Html.TextBoxFor(m => m.FirstName) </div> <div class="dataElem"> <label>LastName</label> @Html.TextBoxFor(m =>m.LastName) </div> <div class="dataElem"> <label>Role</label> @Html.DropDownListFor(m =>m.Role, new SelectList(Enum.GetNames(typeof(MVCHelperStudy.Models.Role)))) </div> <input type="submit" value="Submit" /> } </body> </html>
测试运行:
把表单中间代码替换为:
<div class="dataElem"> <label>PersonId</label> @Html.Editor("PersonId") </div> <div class="dataElem"> <label>FirstName</label> @Html.Editor("FirstName") </div> <div class="dataElem"> <label>LastName</label> @Html.EditorFor(m =>m.LastName) </div> <div class="dataElem"> <label>Role</label> @Html.EditorFor(m => m.Role) </div> <div class="dataElem"> <label>BirthDate</label> @Html.EditorFor(m =>m.BirthDate) </div>
代码说明:使用了Html.Editor替代以前的实现。
看一下生成的html