好的,伙计们。我已经查找了一些方法来做到这一点,因为我厌倦了编写愚蠢的工作来克服 .Net 框架中的这个缺陷。基于几个线程,我编写了以下解决方案。
免责声明,这不是一个完全自动化的解决方案,因此它并不适用于所有人。鉴于我的实现,它有效。也许我的方式会帮助其他人设计出适合他们的东西。
首先,我创建了一个枚举存储库。枚举不必驻留在此处,但它们需要在存储库中可见。
在存储库中,我创建了一个类和一个公共静态属性来公开枚举类型列表。
namespace MyApp.Enums
{
public enum ATS_Tabs { TabOne = 0, TabTwo = 1, TabThree = 2, TabFour = 3, TabFive = 4 };
public class ModelEnums
{
public static IEnumerable<Type> Types
{
get
{
List<Type> Types = new List<Type>();
Types.Add(typeof(ATS_Tabs));
return Types;
}
}
}
}
接下来,我创建了一个模型绑定器并实现了 IModelBinder 接口(参考 kdawg 的评论和链接)。
namespace MyApp.CustomModelBinders
{
public class EnumModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
return Enum.ToObject(Type.GetType(bindingContext.ModelType.AssemblyQualifiedName), Convert.ToInt32(valueResult.AttemptedValue));
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
}
添加一些代码可能有助于确保 valueResult.AttemptedValue 的转换不会失败。
接下来,我遍历了上面创建的枚举类型列表,并为它们添加了模型绑定器(...在 Global.asax.cs 中)。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
foreach (Type type in ModelEnums.Types)
{
ModelBinders.Binders.Add(type, new EnumModelBinder());
}
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
我承认,这不是最直观的方式,但对我来说效果很好。如果我可以优化这个,请随时告诉我。