[英]MVC custom model binder using the default binder for certain form values
我有一个自定义模型绑定器,它被调用进入action方法的特定参数:
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()
方法中的my的表单值创建默认模型绑定器?
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。
这是我找到的一个潜在的解决方案(通过查看默认的模型绑定器源代码),它允许您使用默认的模型绑定器功能来创建字典,列表等。
创建一个新的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);
现在,使用您指定的绑定上下文调用默认模型绑定器,并将正常返回绑定对象。
到目前为止似乎工作...
如果模型绑定器需要使用其他一些表单数据,这意味着您没有将此模型绑定器放在正确的类型上。 模型绑定器的正确类型如下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.