【问题标题】:Add dataAnnotation on demand to validate a form + mvc4按需添加dataAnnotation以验证表单+ mvc4
【发布时间】:2013-07-16 09:23:01
【问题描述】:

我需要验证一个表单,这是我的模型:

 public class Movie {
    public int ID { get; set; }

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

    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }

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

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [StringLength(5)]
    public string Rating { get; set; }
}

我的问题是:我有一个包含 CinemaId 的 querystringParam,当我读取此参数时,我从数据库中读取每个属性的配置是否需要。有时我需要在属性中添加[Required],有时不需要,请问我该怎么做??

【问题讨论】:

标签: c# asp.net-mvc-3 validation asp.net-mvc-4 data-annotations


【解决方案1】:

在@JotaBe 给出的答案的基础上,您可以在 Model 属性本身上使用自定义验证属性。像这样:

条件必需属性

public class ConditionalRequiredAttribute : ValidationAttribute
{
    private const string DefaultErrorMessageFormatString 
                   = "The {0} field is required.";

    private readonly string _dependentPropertyName;

    public ConditionalRequiredAttribute(string dependentPropertyName)
    {
        _dependentPropertyName = dependentPropertyName;
        ErrorMessage = DefaultErrorMessageFormatString;
    }

    protected override ValidationResult IsValid(
                object item, 
                ValidationContext validationContext)
    {
        var property = validationContext
                         .ObjectInstance.GetType()
                         .GetProperty(_dependentPropertyName);

        var dependentPropertyValue = 
                            property
                            .GetValue(validationContext.ObjectInstance, null);

        int value;
        if (dependentPropertyValue is bool 
                           && (bool)dependentPropertyValue)
        {
            /* Put the validations that you need here */
            if (item == null)
            {
              return new ValidationResult(
                  string.Format(ErrorMessageString, 
                                validationContext.DisplayName));
            }
        }

         return ValidationResult.Success;
    }
}

应用属性

这里我有一个类 Movie 并且根据 RatingIsRequired 布尔属性的值需要评级,该布尔属性可以从服务器设置。

public class Movie
{
   public bool RatingIsRequired { get; set; }

   [ConditionallyRequired("RatingIsRequired"]   
   public string Rating { get; set; }
}
  1. 如果RatingIsRequired 设置为true 并且Rating 为空,则ModelState.IsValid 将返回false。
  2. 您还可以编写一个自定义的不显眼的 jquery 验证器来进行客户端启用的验证,这样就可以像常规的 [Required] 属性一样工作。

如果这有帮助,请告诉我。

【讨论】:

    【解决方案2】:

    您必须在控制器操作中修改ModelState

    在您的 post 操作中,加载数据库配置检查每个属性,并将错误添加到 ModelState 属性,如下所示:

    if (/* the property value is wrong */)
    {
      ModelState.AddModelError("propertyName", "message");
    }
    

    这些错误将被视为是由 MVC 框架使用数据注释生成的(向呈现的控件添加样式、出现在错误列表中等等)。

    如果属性是嵌套的,则使用点,例如:"property.subproperty.subproperty" 作为属性名称参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2012-10-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多