3

次のシナリオで実験しています。

最初の GET で、コントローラーはプロパティを持つデフォルト モデルを返しstring[]ます。

ビューで、テキスト ボックスを使用してこのプロパティを表示します。

@Html.TextBoxFor(model => model.MyProperty) 

配列はカンマ区切りのリストとして表示されます。すごい!

問題は、ポストバックすると、リストがその文字列内ですべての項目がコンマで区切られた単一の文字列配列として終了することです。

これを正しい配列に戻すデシリアライザー (おそらく WPF のコンバーターに相当するもの) を提供する方法はありますか?

@Html.EditorFor(...) も使用できることは承知していますが、これにより、配列が不要な個別のテキスト ボックスのリストとしてレンダリングされます。

4

1 に答える 1

4

次のように、文字列配列をバインドするためのカスタム モデル バインダーを作成できます。

public class StringArrayBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string key = bindingContext.ModelName;
        ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (val != null && string.IsNullOrEmpty(val.AttemptedValue) == false)
        {
            bindingContext.ModelState.SetModelValue(key, val);
            string incomingString = ((string[])val.RawValue)[0];

            var splitted = incomingString.Split(',');
            if (splitted.Length > 1)
            {
                return splitted;
            }
        }
        return null;
    }
}

global.asaxそして、アプリケーションの起動時にそれを登録します:

ModelBinders.Binders[typeof(string[])] = new StringArrayBinder();

または、より単純だが再利用性の低いアプローチは次のようになります。

public string[] MyStringPropertyArray { get; set; }

public string MyStringProperty
{
    get
    {
        if (MyStringPropertyArray != null)
            return string.Join(",", MyStringPropertyArray);
        return null;
    }
    set
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            MyStringPropertyArray = value.Split(',');
        }
        else
        {
            MyStringPropertyArray = null;
        }
    }
}

ここで、ビューにバインドしMyStringPropertyます。次に、ビジネス コードでMyStringPropertyArray(からの値が入力された) を使用します。MyStringProperty

于 2013-01-07T11:11:19.260 に答える