我有一个自定义模型绑定器,它采用逗号分隔列表并清除所有空值,然后将其传递给默认模型绑定器。这在 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);
}
}