In MVC 3, I created custom model binders by creating a new class that implemented Systen.Web.Mvc.IModelBinder
, and then registered it inside Global.asax.cs
and inside Application_Start()
using ModelBinders.Binders.Add(typeof(sometype), new MyModelBinder());
In MVC 4 I understand that you are supposed to use System.Web.Http.ModelBinding.IModelBinder
to implement model binders.
So I have two questions:
Why are we supposed to use the model binder from System.Web.Http.ModelBinding
instead of the one from Systen.Web.Mvc
? I don't see it is listed as deprecated anywhere, so what is the problem with the old one?
If I implement my model binder from the System.Web.Http.ModelBinding.IModelBinder
, how do I register it inside my application so it will actually be used?
In the MVC pattern, Model binding maps the HTTP request data to the parameters of a Controllers action method. The parameter can be of a simple type like integers, strings, double etc. or they may be complex types. MVC then binds the request data to the action parameter by using the parameter name.
You can apply the ModelBinder attribute to individual model properties (such as on a viewmodel) or to action method parameters to specify a certain model binder or model name for just that type or action.
How does model binding work in ASP.NET Core MVC. In an empty project, change Startup class to add services and middleware for MVC. Add the following code to HomeController, demonstrating binding of simple types. Add the following code to HomeController, demonstrating binding of complex types.
You can register your model binder in the same way(in the Global.asax.cs) and you can also use the System.Web.Mvc.IModelBinder
interface.
However, the System.Web.Http namespace is basically for the ASP.NET MVC Web API(i.e. for building web services).
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