0

を使用してコレクションにバインドすることは可能ModelBinderAttributeですか?

これが私のアクションメソッドのパラメーターです:

[ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] List<SelectableLookup> classificationItems

そして、これが私のカスタムモデルバインダーです:

public class SelectableLookupAllSelectedModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = bindingContext.Model as SelectableLookup ??
                             (SelectableLookup)DependencyResolver.Current.GetService(typeof(SelectableLookup));

        model.UId = int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue);
        model.InitialState = true;
        model.SelectedState = true;

        return model;
    }
}

このパラメーターの投稿された JSON データは次のとおりです。

"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でグローバルModelBinderとして宣言すると、正常に動作することを追加する必要があります...

4

1 に答える 1

2

カスタム モデル バインダーは、特定のアイテムごとだけでなく、リスト全体に使用されています。IModelBinder を実装して新しいバインダーをゼロから作成しているため、すべての項目をリストに追加したり、リストのプレフィックスを追加したりする必要があります。これは単純なコードではありません。ここで DefaultModelBinder を確認してください。

代わりに、クラスを拡張してDefaultModelBinder、通常どおりに機能させてから、これら 2 つのプロパティを 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 属性を追加することで処理できます。[Bind(Prefix="viewModel")]

最終的に、アクション メソッドのパラメーターは次のようになります。

[Bind(Prefix="viewModel")]
[ModelBinder(typeof(SelectableLookupAllSelectedModelBinder))] 
List<SelectableLookup> classificationItems
于 2013-02-13T19:33:53.520 に答える