How does ASP.NET MVC know how to fill your model to feed your Controller's Action? Does it involve reflection?
Having defined a Model
public class HomeModel {
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Surname")]
public string Surname { get; set; }
}
and having the following Controller
public class HomeController : Controller {
[HttpPost]
public ActionResult Index(HomeModel model) {
return View(model);
}
public ActionResult Index() {
return View();
}
}
by some "magic" mechanism HomeModel model
gets filled up with values by ASP.NET MVC. Does anyone know how?
From some rudimentary tests, it seems it will look at the POST response and try to match the response objects name with your Model's开发者_运维技巧 properties. But to do that I guess it must use reflection? Isn't that inheritably slow?
Thanks
Yes, you are talking about the magic ModelBinder
.
ModelBinder
is responsible for creating a Model and hydrating it with values from the form post-back and performing validation which its result will appear in ModelState
.
Default implementation is DefaultModelBinder but you can plug-in your own.
The DefaultModelBinder indeed uses reflection to set the properties of the model. To be more specific it uses the SetValue method of the PropertyDescriptor class. Of course you can always create a custom model binder to avoid reflection.
精彩评论