1

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

 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]到属性中,有时不,请问我该怎么做?

4

2 回答 2

0

在@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. 有了这个,如果设置为 true 并且 为空,ModelState.IsValid则将返回 false 。RatingIsRequiredRating
  2. 您还可以编写一个自定义的不显眼的 jquery 验证器来进行客户端启用的验证,这样就可以像常规[Required]属性一样工作。

让我知道这是否有帮助。

于 2013-07-17T15:11:56.010 回答
0

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

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

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

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

如果属性是嵌套的,则使用点,如下所示:"property.subproperty.subproperty"用于属性名称参数。

于 2013-07-16T09:33:47.913 回答