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.
IModelBinder
DefaultModelBinder
rather than direct implementation of IModelBinder
, but I don't really see how to leverage the benefitsModelState.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?
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.
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.
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 .
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.
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.
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.
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