2010-04-16 121 views
2

我有这样的模型;ValueProvider.GetValue扩展方法

public class QuickQuote 
{ 
    [Required] 
    public Enumerations.AUSTRALIA_STATES state { get; set; } 

    [Required] 
    public Enumerations.FAMILY_TYPE familyType { get; set; } 

正如你可以看到两个proerties是枚举。

现在我想雇用我自己的模型活页夹,原因是我暂时不打算进入。

所以我有;

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", ...)

这可能吗?

回答

1

是的,你可以有一个扩展方法。这里有一个非常简单的例子来展示你如何写它。

public static class Extensions 
{ 
    public static ValueProviderResult GetModel(this IValueProvider valueProvider, string key) 
    { 
     return valueProvider.GetValue(key); 

    } 
} 

我会考虑的另一件事是使用Enum.IsDefined而不是try catch块。它会提高性能并可能导致更易读的代码。

+0

+1我做到了,非常感谢。 – griegs 2010-04-16 05:43:02

+0

我不能将自己标记为答案,但你的答案非常好,所以...... – griegs 2010-04-16 05:44:45

0

没事的,我明白了。

public static class TryGetValueHelper 
{ 
    public static TEnum TryGetValue<TEnum>(this ModelBindingContext context, string property) 
    { 
     try 
     { 
      TEnum propertyValue = (TEnum)Enum.Parse(typeof(TEnum), context.ValueProvider.GetValue(property).AttemptedValue); 
      return propertyValue; 
     } 
     catch { 
      ModelState modelState = new ModelState(); 
      ModelError modelError = new ModelError("Required"); 
      modelState.Errors.Add(modelError); 
      context.ModelState.Add(context.ModelName + "." + property, modelState); 
     } 

     return default(TEnum); 

    } 
} 
+0

D'oh!同时发布。不过,如果你想摆脱try/catch块,请查看Enum.IsDefined。 – Mac 2010-04-16 05:04:45