Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

c# - Custom model binder for a property

I have the following controller action:

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

Where 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 on every single property instead of the whole model (which I wouldn't prefer as 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<int> and register model binder for this type (this is an option)

  3. 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?

Is there any other solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...