Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom model binder for model inner property

Tags:

asp.net-mvc

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?

like image 645
Andrej Kaurin Avatar asked Dec 22 '09 14:12

Andrej Kaurin


People also ask

Can we create custom model binder?

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.

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

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.

Which interface should be implemented to create custom binder?

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.

What is model binder?

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.


1 Answers

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

like image 111
SDReyes Avatar answered Sep 30 '22 03:09

SDReyes