Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I register a custom model binder somewhere other than Global.asax?

It would be handy to limit the scope of a custom model binder for just a specific controller action method or its entire controller. Hanselman wrote a sentence that implied alternative locations for custom model binder registration but never seemed to finish the thought:

You can either put this Custom Model Binder in charge of all your DateTimes by registering it in the Global.asax

Is it possible to make these registrations at a smaller scope of the controller system? If so, is there any reason to avoid doing so outside of the Global.asax MvcApplication (e.g., performance reasons)?

like image 203
patridge Avatar asked Jun 14 '10 21:06

patridge


People also ask

How can we register a custom model binder in asp net core?

To register custom model binder, we need to create a binder provider. The model binder provider class implement IModelBinderProvider interface. The all built-in model binders have their own model binder providers. We can also specify the type of argument model binder produces, not the input of our model binder.

What is custom model binder in MVC?

Custom Model Binder provides a mechanism using which we can map the data from the request to our ASP.NET MVC Model.


1 Answers

As I was closing the tabs I opened for this question that I hadn't reached before giving up, I found someone with an answer. You can assign a ModelBinderAttribute to your view models:

[ModelBinder(typeof(SomeEditorModelModelBinder))]
public class SomeEditorModel {
    // display model goes here
}
public class SomeEditorModelModelBinder : DefaultModelBinder {
    // custom model binder for said model goes here
}

While it wasn't quite what I was looking for, it is even more specific than registering it for a controller or controller method.

Update

Thanks to Levi's comment pointing out a much better solution. If you are consuming the object with a custom model binder in an MVC action method directly, you can simply decorate that method's parameter with the ModelBinder property.

public ActionResult SomeMethod([ModelBinder(typeof(SomeEditorModelBinder))]SomeEditorModel model) { ... }
like image 170
patridge Avatar answered Sep 30 '22 02:09

patridge