C#MVC5在带有List的模型中进行验证

时间:2015-09-20 23:41:04

标签: c# asp.net-mvc validation asp.net-mvc-5

在一个类中,我有一个允许的静态值列表

private static List<string> allowedClassNames = new List<string> {"Real Estate", "Factored Debt"}; 

我也有该类的属性,我想将其限制为该列表中的值。

        [Required]
        public string assetClassName { get; set; }

我想在模型级别执行此操作,因此它可以在REST或视图上下文中工作。

如何实施强制提交中的值仅限于该列表?

谢谢!

这是我结束的地方 - 尚未完全测试,但是为未来的海报提供一个想法。

    class MustContainAttribute : RequiredAttribute
{
    public string Field { get; private set; }
    List<string> allowed;

    public MustContainAttribute(string validateField)
    {
        this.Field = validateField;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        switch (Field)
        {
            case "assetClassName":
                allowed = new List<string> { "Real Estate", "Factored Debt" }; 
                break;
            default:
                return ValidationResult.Success;
        }

        if (!allowed.Contains(Field))
        {
            return new ValidationResult("Invalid Value");
        }else{
            return ValidationResult.Success;
        }

    }

}

1 个答案:

答案 0 :(得分:1)

创建自定义验证属性:

public class ClassNameRequiredAttribute : RequiredAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {

        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        MyAssetClass myAssetClass = (MyAssetClass)type.GetProperty("MyAssetClass").GetValue(instance, null);

        if (!string.IsNullOrEmpty(myAssetClass.assetClassName))
        {
            if (myAssetClass.allowedClassNames.Contains(myAssetClass.assetClassName))
            {
                return ValidationResult.Success;
            }
        }
        return new ValidationResult(ErrorMessage);
    }
}

在你的模特中:

    [ClassNameRequired(ErrorMessage="Your error message.")]
    public string assetClassName { get; set; }