日期:2014-05-16 浏览次数:20851 次
1. 准备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 }
2. 准备Controller
public class PersonController : Controller { // // GET: /Person/ private readonly Person[] _personData = { new Person {FirstName = "Iori",LastName = "Lan", Role = Role.Admin,PersonId = 1}, new Person {FirstName = "Edwin",LastName = "Sanderson", Role = Role.Admin,PersonId = 2}, new Person {FirstName = "John",LastName = "Griffyth", Role = Role.User,PersonId = 3}, new Person {FirstName = "Tik",LastName = "Smith", Role = Role.User,PersonId = 4}, new Person {FirstName = "Anne",LastName = "Jones", Role = Role.Guest,PersonId = 5} }; public ActionResult PersonInfo(int id) { Person dataItem = _personData.Where(p => p.PersonId == id).First(); return View("PersonInfo", dataItem); } }
3. View(PersonInfo.cshtml)
@model MVCModel.Models.Person @{ ViewBag.Title = "Index"; } <h2>Person</h2> <div><label>ID:</label>@Html.DisplayFor(m=> m.PersonId)</div> <div><label>FirstName:</label>@Html.DisplayFor(m => m.FirstName)</div> <div><label>LastName:</label>@Html.DisplayFor(m => m.LastName)</div> <div><label>Role:</label>@Html.DisplayFor(m=> m.Role)</div>
4. 运行
Scenario 1 : 不传递id
Scenario 2 : 传递一个正确类型的id
Scenario 3: 传递一个错误类型的id
结果:只有Scenario 2代码是正确工作的,也就是对于valuetype来说,不给参数或者错误类型,model都无法完成参数解析。
本章重点在Action Invoker到GetParameter这个过程,Modelbinding的工作就是负责给Action搞定Parameter,而信息Request中都有。
Model binder的搜索范围和顺序:
Request.Form |
RouteData.Values |
Request.QueryString |
Request.Files |
以刚才的Scenario 为例,当id被解析为参数时,modelbinder会从Form,RouteData.Values,QueryString,Files中找到key为id的值,找到了就返回。
对于值类型,为了避免传参类型不对或者为空model直接抛异常,可以给一个默认值参数,或者给一个Nullable类型(int