Andrej Kaurin
Andrej Kaurin

Reputation: 11642

Custom model binder for model inner property

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?

Upvotes: 7

Views: 1578

Answers (2)

SDReyes
SDReyes

Reputation: 9954

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

Upvotes: 1

Victor Gelmutdinov
Victor Gelmutdinov

Reputation: 489

Actually, If you will put in some Edit/Create View with Model of your MyModel class something like this:

<%= Html.TextBox("Meta.Prop1") %>

where Prop1 is property of your MyOtherModel class, then

UpdateModel(model);

will populate textbox value to your custom submodel property. And back, textbox value would be populated with that submodel value as well.

So, once you update your current model, you are updating submodels too.

Upvotes: 0

Related Questions