有没有办法让DefaultModelBinder在绑定到List <Enum>时忽略空项

Jer*_*eir 3 asp.net-mvc modelbinders asp.net-mvc-2

我有一个场景,我想改变DefaultModelBinder在绑定到枚举列表时的行为.

我有一个枚举......

public enum MyEnum { FirstVal, SecondVal, ThirdVal }
Run Code Online (Sandbox Code Playgroud)

和一个模型的类......

public class MyModel
{
    public List<MyEnum> MyEnums { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并且POST正文是......

MyEnums=&MyEnums=ThirdVal
Run Code Online (Sandbox Code Playgroud)

目前,在模型绑定之后,MyEnums属性将包含...

[0] = FirstVal
[1] = ThirdVal
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉模型绑定器忽略发布数据中的空值,以便MyEnums属性看起来如下所示?

[0] = ThirdVal
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

您可以为MyModel编写自定义模型绑定器:

public class MyModelModelBinder : DefaultModelBinder
{
    protected override void SetProperty(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        PropertyDescriptor propertyDescriptor, 
        object value)
    {
        if (value is ICollection<MyEnum>)
        {
            var myEnums = controllerContext.HttpContext.Request[propertyDescriptor.Name];
            if (!string.IsNullOrEmpty(myEnums))
            {
                var tokens = myEnums.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                value = tokens.Select(x => (MyEnum)Enum.Parse(typeof(MyEnum), x)).ToList();
            }
        }
        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

注册地址Application_Start:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(MyModel), new MyModelModelBinder());
}
Run Code Online (Sandbox Code Playgroud)

更新:

根据评论部分的要求,这里是如何使以前的活页夹更通用:

protected override void SetProperty(
    ControllerContext controllerContext, 
    ModelBindingContext bindingContext, 
    PropertyDescriptor propertyDescriptor, 
    object value)
{
    var collection = value as IList;
    if (collection != null && collection.GetType().IsGenericType)
    {
        var genericArgument = collection
            .GetType()
            .GetGenericArguments()
            .Where(t => t.IsEnum)
            .FirstOrDefault();

        if (genericArgument != null)
        {
            collection.Clear();
            var enumValues = controllerContext.HttpContext
                .Request[propertyDescriptor.Name];
            var tokens = enumValues.Split(
                new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var token in tokens)
            {
                collection.Add(Enum.Parse(genericArgument, token));
            }
        }
    }
    base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
Run Code Online (Sandbox Code Playgroud)