views:

71

answers:

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  A: 

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.

Paul
This looks like a perfect solution. I'll give it a try and get back to you :-)
Russell Giddings
A: 
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?

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