My model is like this
public class MyModel
{
string ID {get;set;}
string Title {get;set;}
MyOtherModel Meta {get;set;}
}
How to define custom model binder for type (MyOtherModel) so when default binder binds MyModel it calls custom model binder for 'Meta' property. I registered it in App start like:
ModelBinders.Binders[typeof(MyOtherModel)] = new MyCustomBinder();
but this doesn't work. Any idea or any good article with more infor regarding to model binders?
We can apply custom model binder using ModelBinder attribute by defining attributes on action method or model. If we are using this method (applying attribute on action method), we need to define this attribute on every action methods those want use this custom binding.
Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.
For creating a custom model binder class, we have to inherit from IModelBinder interface. This interface has an async method named "BindModelAsync" and it has a parameter of type ModelBindingContext. The ModelBindingContext class provides the context that model on which the binder acts.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
There is an article about collections that touches a bit the complex type mapping stuff:
Collections and a bit about complex types
In the other hand this article could give you some useful tips:
http://odetocode.com/Blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx
I suggest you as a workaround to use a model binder for MyModel class, it's not a perfect solution but you can refactor it easily once you discover a better solution. : )
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