MVC自定义模型绑定器使用默认绑定器表示某些表单值

时间:2012-07-10 08:31:54

标签: c# asp.net-mvc model-binding

我有一个自定义模型绑定器,可以为进入操作方法的特定参数调用:

public override ActionResult MyAction(int someData, [ModelBinder(typeof(MyCustomModelBinder))]List<MyObject> myList ... )

这很好用 - 按预期调用活页夹。但是,我想为Request.Form集合中的某些 addtional 值调用默认模型绑定器。表单键已命名 像这样:

dataFromView[0].Key
dataFromView[0].Value
dataFromView[1].Key
dataFromView[1].Value

如果我在操作方法上添加IDictionary作为参数,默认模型绑定器很好地将这些值转换为IDictionary。

但是,我想在模型活页夹级别操作这些值(以及上面的原始List对象)。

有没有办法让我的默认模型绑定器从我自定义模型绑定器的BindModel()方法中的表单值创建此字典?

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    //Get the default model binder to provide the IDictionary from the form values...           
}

我尝试使用bindingContext.ValueProvider.GetValue但是当我试图转换为IDictionary时,它似乎总是返回null。

2 个答案:

答案 0 :(得分:4)

这是我找到的潜在解决方案(通过查看默认的模型绑定器源代码),它允许您使用默认的模型绑定器功能来创建字典,列表等。

创建一个新的ModelBindingContext,详细说明您需要的绑定值:

var dictionaryBindingContext = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(IDictionary<long, int>)),
                ModelName = "dataFromView", //The name(s) of the form elements you want going into the dictionary
                ModelState = bindingContext.ModelState,
                PropertyFilter = bindingContext.PropertyFilter,
                ValueProvider = bindingContext.ValueProvider
            };

var boundValues = base.BindModel(controllerContext, dictionaryBindingContext);

现在使用您指定的绑定上下文调用默认模型绑定器,并将正常返回绑定对象。

到目前为止似乎工作......

答案 1 :(得分:2)

如果您的模型活页夹需要使用其他一些表单数据,这意味着您没有将此模型活页夹定位在正确的类型上。模型绑定器的正确类型如下:

public class MyViewModel
{
    public IDictionary<string, string> DataFromView { get; set; }
    public List<MyObject> MyList { get; set; }
}

然后:

public class MyCustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = base.BindModel(controllerContext, bindingContext);

        // do something with the model

        return model;
    }
}

然后:

[HttpPost]
public ActionResult Index([ModelBinder(typeof(MyCustomModelBinder))] MyViewModel model)
{
    ...
}

这假设发布了以下数据:

dataFromView[0].Key
dataFromView[0].Value
dataFromView[1].Value
dataFromView[1].Key
myList[0].Text
myList[1].Text
myList[2].Text