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
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
Also, MVC relies heavily on reflection, which allows you to inspect types at runtime using strings. Reflection is used in many programming frameworks.
MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With