在 MSDN 中是這麼定義的
IModelBinder
Defines the methods that are required for a model binder.
ModelBinder在 ASP.NET 中最主要的作用是讓POST回來的值在進入 Cotroller 之前可以先做一點整理。讓 Controller 可以直接使用已整理後的 Class 而不是一堆 Form 上面的資料
How.
要使用 ModelBinder 有幾個步驟
1. 建立 ModelBinder, 要 Implement IModelBinder
public class Service1ModelBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
Service1 service = new Service1(new User())
{
Name = request["name"]
..... other fields you need
};
return service;
}
#endregion
}
2.定義 這個 ModelBinder 是 Bind 那個Class,這個要寫在 HttpApplication 中,一般是 Global.asax.cs
protected void Application_Start()
{
//ModelBinders
ModelBinderDictionary binders = System.Web.Mvc.ModelBinders.Binders;
binders[typeof(Service1)] = new Service1ModelBinder();
RegisterRoutes(RouteTable.Routes);
}
3. 改寫 Controller 的 method
[AcceptVerbs("POST")]
public ActionResult Index(Service1 service)
{
ViewData["Message"] = service.Name;
return View();
}
<% Html.BeginForm(); %>
<input type="text" name="name" value="Service1" />
<button type="submit">Submitbutton>
<%Html.EndForm(); %>
如此一來,在我們按下按鈕時會先觸發 ModelBinder 再將 ModelBinder 過後的 object 送給 Controller
Reference
IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing
IModelBinder Interface