(一)理解模型绑定
模型绑定是HTTP请求与C#方法之间的一个桥梁,它根据 Action 方法中的 Model 类型创建 .NET 对象,并将 HTTP 请求数据经过转换赋给该对象。
(二)默认的模型绑定器
应用程序有多个绑定器,大多数的都是依赖与内置绑定器类---DefaultModelBinder,一般情况下,模型绑定器搜索4个路径,如下所示。
源 | 描述 |
---|---|
Request.Form | HTML表单提供的值 |
RouteDate.Values | 使用应用程序路由获取的值 |
Request.QueryString | 包含在URL的请求字符串里面的数据 |
Request.Files | 作为请求部分被上传的文件 |
(三)代码示范
1.首先在Models下面创建Person类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCModels.Models
{
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 Role Role { get; set; }
}
public enum Role
{
Admin,
User,
Guest,
}
public class Address
{
public string Line { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
}
2.在Controllers中的HomeController中编写如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCModels.Models;
namespace MVCModels.Controllers
{
public class HomeController : Controller
{
private Person[] personDate = {
new Person { PersonId = 1, FirstName = "Adam", LastName = "Freeeman", Role = Role.Admin},
new Person { PersonId = 2, FirstName = "Jacqui", LastName = "Griffyth", Role = Role.User},
new Person { PersonId = 1, FirstName = "John", LastName = "Smith", Role = Role.Guest},
};
public ActionResult Index( int id = 1 )
{
Person dataItem = personDate.Where(p => p.PersonId == id).First();
return View(dataItem);
}
public ActionResult CreatePerson()
{
return View(new Person());
}
[HttpPost]
public ActionResult CreatePerson(Person model)
{
return View("Index",model);
}
}
}
3.在视图(Views)中添加createPerson视图,代码示例如下
@model MVCModels.Models.Person
@{
ViewBag.Title = "CreatePerson";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CreatePerson</h2>
@using (Html.BeginForm())
{
<div>
<label>
@Html.LabelFor(m => m.PersonId);
@Html.LabelFor(m => m.PersonId);
</label>
</div>
<div>
<label>
@Html.LabelFor(m => m.FirstName);
@Html.EditorFor(m => m.FirstName);
</label>
</div>
<div>
<label>
@Html.LabelFor(m => m.LastName);
@Html.EditorFor(m => m.LastName);
</label>
</div>
<div>
<label>
@Html.LabelFor(m => m.Role);
@Html.EditorFor(m => m.Role);
</label>
</div>
<button type="submit">Submit</button>
}
4.最后在index视图中再进行代码编写,代码示例如下
@model MVCModels.Models.Person
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Person</h2>
<div>
<label>ID:</label>
@Html.DisplayFor(m => m.PersonId)
</div>
<div>
<label>First Name:</label>
@Html.DisplayFor(m => m.FirstName)
</div>
<div>
<label>Role</label>
@Html.DisplayFor(m => m.Role)
</div>
以上的代码完全编写完了之后,就可以进行运行了