3

我有一个场景,我想更改 DefaultModelBinder 如何绑定到枚举列表的行为。

我有一个枚举...

public enum MyEnum { FirstVal, SecondVal, ThirdVal }

和一个模型类...

public class MyModel
{
    public List<MyEnum> MyEnums { get; set; }
}

POST 正文是……

MyEnums=&MyEnums=ThirdVal

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

[0] = FirstVal
[1] = ThirdVal

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

[0] = ThirdVal
4

1 回答 1

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);
    }
}

注册于Application_Start

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

更新:

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

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);
}
于 2010-02-26T09:34:59.173 回答