我正在 Mvc 应用程序中创建自定义模型绑定器,我想将字符串解析为枚举值并将其分配给模型属性。我已经让它覆盖了该BindProperty
方法,但我也注意到有一个SetProperty
方法。
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
switch (propertyDescriptor.Name)
{
case "EnumProperty":
BindEnumProperty(controllerContext, bindingContext);
break;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
private static void BindEnumProperty(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var formValue = controllerContext.HttpContext.Request.Form["formValue"];
if (String.IsNullOrEmpty(formValue))
{
throw new ArgumentException();
}
var model = (MyModel)bindingContext.Model;
model.EnumProperty = (EnumType)Enum.Parse(typeof(EnumType), formValue);
}
我不确定两者之间有什么区别以及我是否以推荐的方式这样做。