What is model binding in ASP.NET MVC, Why is it needed? Can someone give simple example , Can model binding be achieved by checking create strongly typed view?
Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.
The model binding system: Retrieves data from various sources such as route data, form fields, and query strings. Provides the data to controllers and Razor pages in method parameters and public properties.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
So the two-way data binding means we can perform both read and write operations. In our previous article Data Binding in Spring MVC with Example, we have discussed how to write-to-variable task and in this article, we mainly focus on the read-from-a-variable task.
ModelBinding
is the mechanism ASP.NET MVC uses to create strongly-typed objects (or fill primitive-type parameters) from the input stream (usually an HTTP request).
For example, consider this Person
model:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Now, you have some Action
in some Controller
that's expecting a Person
type as a parameter:
public class HomeController : Controller
{
public ActionResult EditPersonDetails(Person person)
{
// ...
}
}
The Model-Binder
is then responsible to fill that person
parameter for you. By default it does it by consulting the ValueProviders
collection and asking for the value of each property in the (to be bound) model.
More on Value-Providers and Model-Binders on http://haacked.com/archive/2011/06/30/whatrsquos-the-difference-between-a-value-provider-and-model-binder.aspx/
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