Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register a custom model binder in MVC 4

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:

  1. 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?

  2. 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?

like image 782
Øyvind Bråthen Avatar asked Apr 11 '13 12:04

Øyvind Bråthen


People also ask

What is custom model binder in MVC?

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.

How can we use custom model binder in asp net core?

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 do I bind a model to view in MVC core?

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.


1 Answers

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

like image 161
laszlokiss88 Avatar answered Oct 19 '22 23:10

laszlokiss88