Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices when Implementing IModelBinder [closed]

I'm looking for a set of best practices to use when implementing IModelBinder.

I've read three different MVC books and each one does some slightly different stuff in their implementations without any real explanation.

  • The Hanselman, Haack, Guthrie, Conery book doesn't even mention IModelBinder
  • Palermo recommends extending DefaultModelBinder rather than direct implementation of IModelBinder, but I don't really see how to leverage the benefits
  • Sanderson mentions updating existing Model instances, as well as calling ModelState.SetModelValue() to follow convention.

I just want to make sure that my model binders are following conventions, and that I properly understand the entire ModelBindingContext.

Any tips, tricks, GOOD tutorials to recommend?

like image 757
nikmd23 Avatar asked Oct 11 '09 11:10

nikmd23


People also ask

What is the purpose of implementing the BindModel () method on the IModelBinder interface?

MVC uses following types for Model Binding: IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModel method. This method is responsible for binding a model to some values using ControllerContext and BindingContext.

What interface and method need to be implemented for a custom model binder?

To create custom model binder class, it needs to inherit from IModelBinder interface. This interface has async method named "BindModelAsync" and it has parameter of type ModelBindingContext. The ModelBindingContext class provides the context that model binder functions.

What is the purpose of model binding?

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. Converts string data to .

What is a correct use case for creating a custom model binder in asp net core?

You might need to transform the input prior to binding it. For example, when you have a key that can be used to look up model data. You can use a custom model binder to fetch data based on the key.


2 Answers

K Scott Allen has some tips about Model Binding: http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx.

like image 74
hwiechers Avatar answered Oct 05 '22 21:10

hwiechers


I inherited from DefaultModelBinder, because it automatically binds basic properties in entity. I enhanced it, so it binds also navigation properties. My binder performs inherited binding first and then searches for additional, navigation property values in form. I think that Your approach should depend on what You really want to do. You can also use reflector and see what really stands behind default binder. This may convince You to inherit.

like image 32
LukLed Avatar answered Oct 05 '22 22:10

LukLed