2

Within an ASP.Net MVC model binder is it possible to create an object of the bound type and then update the properties on it.

e.g.

public override object BindModel(ControllerContext controllerContext,
    ModelBindingContext bindingContext)
{
    ParentType boundModel = null;
    if (bindingContext.ModelType == typeof(ParentType))
    {
        var myFactory = new MyFactory();
        var someValue = bindingContext.ValueProvider.GetValue
            ("someFieldId").AttemptedValue;
        ChildType child = myFactory.Create(someValue);
        BindModel(child);
        boundModel = child;
    }
    return boundModel;
}

In this code I want to know if there is something similar to the BindModel(child) call, kind of like TryModelUpdate() from a controller?

1
  • I have two child classes and which one is instantiated is based on a drop down list with id "someFieldId". So I would like to instantiate the Child class using the factory then update all the Parent properties from the form using a TryUpdateModel / BindModel call. I would then like the bound model passed to the controller. Commented Feb 19, 2010 at 17:49

3 Answers 3

2

I think a better approach to your problem would be to derive from the DefaultModelBinder (which I think you probably are) and then override the CreateModel method rather than the BindModel method.

By returning your Child object from that, you should be along the path you're looking for.

Sign up to request clarification or add additional context in comments.

1 Comment

This looks like a perfect solution. I'll give it a try and get back to you :-)
0
public override object BindModel(ControllerContext controllerContext, 
                                 ModelBindingContext bindingContext)
{
    ParentType boundModel = null;
    if (bindingContext.ModelType == typeof(ParentType))
    {
        var myFactory = new MyFactory();
        var someValue = bindingContext.ValueProvider
                                      .GetValue("someFieldId").AttemptedValue;
        ChildType child = myFactory.Create(someValue);
        BindModel(child);
        boundModel = child;
    }

    // change here
    bindingContext.ModelMetadata.Model = boundModel;
    return BindModel(controllerContext, bindingContext);
}

How about this?

1 Comment

Unfortunately the method 'BindModel(child)' doesn't exist. That was the issue with my example code. :-(
0

The binder simply need the same names in class properties and the field value, calling updatemodel will place any matching values into the model.

So you should be able to just create either type of class and call updatemodel ???

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.