我有一个这样的模型;
public class QuickQuote
{
[Required]
public Enumerations.AUSTRALIA_STATES state { get; set; }
[Required]
public Enumerations.FAMILY_TYPE familyType { get; set; }
如您所见,这两个属性是枚举。
现在我想使用我自己的模型活页夹,因为我现在不会费心进入。
所以我有;
public class QuickQuoteBinder : DefaultModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
quickQuote = new QuickQuote();
try
{
quickQuote.state = (Enumerations.AUSTRALIA_STATES)
Enum.Parse(typeof(Enumerations.AUSTRALIA_STATES),
bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".state").AttemptedValue);
}
catch {
ModelState modelState = new ModelState();
ModelError err = new ModelError("Required");
modelState.Errors.Add(err);
bindingContext.ModelState.Add(bindingContext.ModelName + ".state", modelState);
}
问题是对于每个属性,并且有堆,我需要做整个 try catch 块。
我想我可能会创建一个扩展方法,它可以为我完成整个块,我需要传入的只是模型属性和枚举。
所以我可以做类似的事情;
quickQuote.state = bindingContext.ValueProvider.GetModelValue("state", ...)
等等
这可能吗?