tags:

views:

77

answers:

1

Hello!

I have a following controller action:

[HttpPost]
public ViewResult DoSomething(MyModel model)
{
  // do something
  return View();
}

MyModel looks like this:

public class MyModel
{
  public string PropertyA {get; set;}
  public IList<int> PropertyB {get; set;}
}

So DefaultModelBinder should bind this without a problem. The only thing is that I want to use special/custom binder for binding PropertyB and I also want to reuse this binder. So I thought that solution would be to put a ModelBinder attribute before the PropertyB which of course doesn't work (ModelBinder attribute is not allowed on a properties). I see two solutions:

1.) To use action parameters instead of model which I don't prefer (the model has a lot of properties...) like this:

public ViewResult DoSomething(string propertyA, [ModelBinder(typeof(MyModelBinder))] propertyB) ...

2.) To create a new type lets say MyCustomType: List and register model binder for this type (this is an option)

Is there any other, third solution? Maybe to create a binder for MyModel, override BindProperty and if the property is "PropertyB" bind the property with my custom binder. Is this possible?

Thanks for your answers...

+1  A: 

override BindProperty and if the property is "PropertyB" bind the property with my custom binder

That's a good solution, though instead of checking "is PropertyB" you better check for your own custom attributes that define property-level binders, like

[PropertyBinder(typeof(PropertyBBinder))]
public IList<int> PropertyB {get; set;}

You can see an example of BindProperty override here.

queen3