Binding Data to an Existing Object in Asp.net MVC
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").AttemptedValu开发者_高级运维e;
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?
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.
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?
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 ???
精彩评论