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