Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 665
devoured elysium Avatar asked Feb 16 '11 11:02

devoured elysium


People also ask

How pass data from controller model in ASP.NET MVC?

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.

How does MVC know which controller to use?

Also, MVC relies heavily on reflection, which allows you to inspect types at runtime using strings. Reflection is used in many programming frameworks.

How does the controller knows which view to return?

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).


1 Answers

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.

like image 63
Aliostad Avatar answered Nov 15 '22 21:11

Aliostad