コンマ区切りのリストを取得し、空の値を消去してから、デフォルトのモデル バインダーに渡すカスタム モデル バインダーがあります。これは ASP.NET MVC Preview 2 で機能しましたが、RC2 にアップグレードすると、ValueProvider のインターフェイスには GetValue() メソッドしかなく、[] アクセサーがないため、以下はコンパイルされません。以下で行っていることは、バインディング コンテキストの他のメカニズムを通じて可能ですか? このような単純な状況では、本格的なモデル バインダーを作成する必要はありません。主な目標は、値が List<SomeEnum> にバインドされるときであり、空の値はスキップされます。
public class EnumListModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider[bindingContext.ModelName];
string[] rawValues = (string[])result.RawValue;
var newValues = new List<string>();
foreach (string value in rawValues)
{
if (!String.IsNullOrEmpty(value))
{
newValues.Add(value);
}
}
string newValuesAttempted = String.Join(",", newValues.ToArray());
// overwrite the ValueProviderResult with the cleaned up csv list
// this is the part I'm not sure how to implement using the interface
bindingContext.ValueProvider[bindingContext.ModelName] =
new ValueProviderResult(newValues.ToArray(), newValuesAttempted, result.Culture);
return System.Web.Mvc.ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
}
}