简体   繁体   English

C#MVC5在具有列表的模型中进行验证

[英]C# MVC5 Validate in Model with a List

Within a Class I have a Static List of values which are allowed 在一个类中,我有一个允许使用的静态值列表

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

And I also have an attribute of that class, which I want to restrict to being values in that list. 而且我还有该类的一个属性,我想将其限制为该列表中的值。

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

I want to do this at the model level, so it works in either a REST or view context. 我想在模型级别执行此操作,因此它可以在REST或视图上下文中使用。

How would I implement forcing the value in the submission to be limited to that list? 我将如何实施强制将提交中的值限制为该列表?

Thanks! 谢谢!

Here's Where I wound up - Not fully tested yet, but to give an idea to future posters. 这就是我要解决的地方-尚未经过全面测试,但可以为将来的海报提供一个思路。

    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;
        }

    }

}

Create a custom validation attribute: 创建一个自定义验证属性:

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);
    }
}

And in your model: 在您的模型中:

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

As mentioned in the comments you can create your own ValidationAttribute. 如评论中所述,您可以创建自己的ValidationAttribute。 This is useful if you have this validation on multiple models or if you want to implement client side validation as well (JavaScript) 如果您在多个模型上进行了此验证,或者您还想实现客户端验证(JavaScript),这将非常有用

However, A quick and easy way to do one off validations like this is the IValidatableObject. 但是,一种简单的一次性验证方法是IValidatableObject。 You can use it as follows: 您可以按以下方式使用它:

public class AssetModel:IValidatableObject
{
    private static List<string> allowedClassNames = new List<string> {"Real Estate", "Factored Debt"};

    [Required]
    public string assetClassName { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!allowedClassNames.Contains(assetClassName)
        {
            yield new ValidationResult("Not an allowed value", new string[] { "assetClassName" } );
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM