我的 Controller 中有一个方法接受一个对象作为参数并返回一个 JsonResult .此对象的属性之一是具有三个可能值的枚举。我假设当客户端为该属性传入一个 int 时,它会填充枚举,但事实并非如此,它默认为 0 并且枚举设置为第一个可能的选择。
有什么建议吗?
最佳答案
注意:这已在 MVC 4 中得到解决。如果升级到 MVC 4 对您的项目来说是一个可行的选择,那么这就是您开始模型绑定(bind)到枚举所要做的全部工作。
也就是说,如果您仍然需要它,这里是 MVC 3 的解决方法。
问题出在 MVC 中的默认模型绑定(bind)器上。正确的整数值使其进入模型联编程序,但联编程序未编码以映射到枚举的整数值。如果传入的值是包含枚举命名值的字符串,则它会正确绑定(bind)。问题在于,当您使用 Json()
方法将 C# 对象解析为 JSON 时,它会将整数值作为枚举值发送,而不是命名值。
对此最简单和最透明的修复是覆盖默认模型绑定(bind)器并编写一些自定义逻辑来修复它绑定(bind)枚举的方式。
像这样创建一个新类。
namespace CustomModelBinders { /// <summary> /// Override for DefaultModelBinder in order to implement fixes to its behavior. /// This model binder inherits from the default model binder. All this does is override the default one, /// check if the property is an enum, if so then use custom binding logic to correctly map the enum. If not, /// we simply invoke the base model binder (DefaultModelBinder) and let it continue binding as normal. /// </summary> public class EnumModelBinder : DefaultModelBinder { /// <summary> /// Fix for the default model binder's failure to decode enum types when binding to JSON. /// </summary> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { var propertyType = propertyDescriptor.PropertyType; if (propertyType.IsEnum) { var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (null != providerValue) { var value = providerValue.RawValue; if (null != value) { var valueType = value.GetType(); if (!valueType.IsEnum) { return Enum.ToObject(propertyType, value); } } } } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); } } }
然后只需在您的 Global.asax 文件中注册它。
protected override void OnApplicationStarted() { base.OnApplicationStarted(); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); // Register your new model binder ModelBinders.Binders.DefaultBinder = new EnumModelBinder(); }
就是这样。枚举现在将正确绑定(bind)到 JSON 对象。
http://www.codetunnel.com/how-to-bind-to-enums-on-json-objects-in-aspnet-mvc-3
关于c# - 模型绑定(bind)到 ASP.NET MVC 3 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6051756/