Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

modelbinders - ASP.NET MVC - Mixing Custom and Default Model Binding

I have a type:

public class IssueForm
{
    Order Order {get; set;}
    Item Item {get; set;}
    Range Range {get; set;}
}

I created a custom model binder due to requirements on Order and Item, but Range could still use the Default Model Binder.

Is there a way from within my custom model binder to call the default model binder to return a Range object? I think I just have to just setup ModelBindingContext correctly, but I don't know how.


EDIT

Looking at the first comment and answer -- it seems like inheriting from the default model binder could be useful.

To add more specifics for my setup so far I have:

public IssueFormModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        Order = //code to pull the OrderNumber from the context and create an Order
        Item = //code to pull the ItemNumber from the context and create an Item

        IssueForm form = IssueFormFactory.Create(Order, Item);

        form.Range = // ** I'd like to replace my code with a call to the default binder **

        return form
    }
}

This might be a stupid way of doing it... this is my first model binder. Just pointing out my current implementation.


EDIT #2

So the answers to override BindProperty will work if I can hook into like a "I'm all done binding" method and call the Factory method with the properties.

I guess I really should look at the DefaultModelBinder implementation and quit being stupid.

question from:https://stackoverflow.com/questions/970335/asp-net-mvc-mixing-custom-and-default-model-binding

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

1 Reply

0 votes
by (71.8m points)

Try something like this:

public class CustomModelBinder :  DefaultModelBinder {
    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) {
        if(propertyDescriptor.Name == "Order") {
            ...
            return;
        }

        if(propertyDescriptor.Name == "Item") {
            ...
            return;
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...