Asp.net mvc 3 MVC 3 ModelBinding到具有ModelBinderAttribute的集合

Asp.net mvc 3 MVC 3 ModelBinding到具有ModelBinderAttribute的集合,asp.net-mvc-3,model-binding,Asp.net Mvc 3,Model Binding,是否可以使用modelbinderatAttribute绑定到集合 以下是我的操作方法参数: [ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] List<SelectableLookup> classificationItems 下面是该参数的发布JSON数据: [ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] List<Sele

是否可以使用
modelbinderatAttribute
绑定到集合

以下是我的操作方法参数:

[ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] List<SelectableLookup> classificationItems
下面是该参数的发布JSON数据:

[ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] List<SelectableLookup> classificationItems
“分类项目”:[“19”、“20”、“21”、“22”]}

以下是ValueProvider的看法:

viewModel.classificationItems[0]
AttemptedValue=“19”
viewModel.classificationItems[1]
AttemptedValue=“20”
viewModel.classificationItems[2]
AttemptedValue=“21”
viewModel.classificationItems[3]
AttemptedValue=“22”

这目前不起作用,因为首先有一个前缀(“viewModel”),我可以对其进行排序,但其次是
bindingContext。ModelName
是“classificationItems”,它是绑定到的参数的名称,而不是列表中的索引项,即“classificationItems[0]”


我应该补充一点,当我在global.asax中将此活页夹声明为全局模型活页夹时,它可以正常工作…

您的自定义模型活页夹将用于整个列表,而不仅仅用于每个特定项目。当您通过实现IModelBinder从头开始编写新的活页夹时,您需要处理将所有项目添加到列表和列表前缀等。这不是简单的代码,请检查DefaultModelBinder

相反,您可以扩展
DefaultModelBinder
类,让它像往常一样工作,然后将这两个属性设置为true:

public class SelectableLookupAllSelectedModelBinder: DefaultModelBinder
{

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        //Let the default model binder do its work so the List<SelectableLookup> is recreated
        object model = base.BindModel(controllerContext, bindingContext);

        if (model == null)
            return null; 

        List<SelectableLookup> lookupModel = model as List<SelectableLookup>;
        if(lookupModel == null)
            return model;

        //The DefaultModelBinder has already done its job and model is of type List<SelectableLookup>
        //Set both InitialState and SelectedState as true
        foreach(var lookup in lookupModel)
        {
            lookup.InitialState = true;
            lookup.SelectedState = true;
        }

        return model;          
    }

更改操作方法的签名以接收具有集合成员的对象。
[Bind(Prefix="viewModel")]
[ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] 
List<SelectableLookup> classificationItems