如果您检查 POST 正文,数据已发送,但只是未正确拾取。这是因为 MVC 不能很好地处理标志枚举。有人谁回答的 https://stackoverflow.com/questions/9264927/model-bind-list-of-enum-flags#9267201一个类似的问题描述了这一点:
一般来说,我在设计视图模型时避免使用枚举,因为它们不与 ASP.NET MVC 的帮助程序和开箱即用的模型绑定器一起使用。它们在您的域模型中非常好,但对于视图模型,您可以使用其他类型。
回答问题的人还提供了如何绑定标志枚举的完整答案。您基本上需要做的是创建自己的自定义模型绑定器来处理标志枚举。在另一篇名为ASP.Net MVC 标志枚举模型绑定器 http://itq.nl/asp-net-mvc-flag-enumeration-model-binder/我找到了一个例子,我将复制相关代码。
添加一个名为CustomModelBinder
如下:
public class CustomModelBinder : DefaultModelBinder
{
protected override object GetPropertyValue(
ControllerContext controllerContext,
ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor,
IModelBinder propertyBinder)
{
var propertyType = propertyDescriptor.PropertyType;
// Check if the property type is an enum with the flag attribute
if (propertyType.IsEnum && propertyType.GetCustomAttributes(true).Any())
{
var providerValue = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
if (providerValue != null)
{
var value = providerValue.RawValue;
if (value != null)
{
// In case it is a checkbox list/dropdownlist/radio
// button list
if (value is string[])
{
// Create flag value from posted values
var flagValue = ((string[])value)
.Aggregate(0, (acc, i)
=> acc | (int)Enum.Parse(propertyType, i));
return Enum.ToObject(propertyType, flagValue);
}
// In case it is a single value
if (value.GetType().IsEnum)
{
return Enum.ToObject(propertyType, value);
}
}
}
}
return base.GetPropertyValue(controllerContext,
bindingContext,
propertyDescriptor,
propertyBinder);
}
}
然后在Global.asax.cs中Application_Start
方法注册自定义模型绑定器如下:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// Register custom flag enum model binder
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}
这应该有效。
Source: http://itq.nl/asp-net-mvc-flag-enumeration-model-binder/ http://itq.nl/asp-net-mvc-flag-enumeration-model-binder/