2

我有一个这样的模型;

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

这可能吗?

4

2 回答 2

1

是的,您可以使用扩展方法。这是一个非常简单的示例来展示您将如何编写它。

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

    }
}

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

于 2010-04-16T05:04:13.053 回答
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);

    }
}
于 2010-04-16T04:56:44.890 回答