2

在 ASP.Net MVC 模型绑定器中,可以创建绑定类型的对象,然后更新其属性。

例如

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;
}

在这段代码中,我想知道是否有类似于 BindModel(child) 调用的东西,有点像来自控制器的 TryModelUpdate()?

4

3 回答 3

2

我认为解决您的问题的更好方法是从 DefaultModelBinder (我认为您可能是)派生,然后覆盖 CreateModel 方法而不是 BindModel 方法。

通过从中返回您的 Child 对象,您应该沿着您正在寻找的路径。

于 2010-02-19T19:29:17.660 回答
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);
}

这个怎么样?

于 2010-02-21T15:56:11.213 回答
0

binder 只需要在类属性和字段值中具有相同的名称,调用 updatemodel 会将任何匹配的值放入模型中。

所以你应该能够创建任一类型的类并调用 updatemodel ???

于 2010-11-18T10:59:59.117 回答