简体   繁体   English

ASP.NET MVC模型验证

[英]Asp.net MVC model validating

I`m new On Asp.net Mvc (4) 我是Asp.net Mvc的新手(4)

can I call a function to validate a model property ( It is more than REQUIRED , MAXLENGHT...) 我可以调用一个函数来验证模型属性吗(超过了REQUIRED,MAXLENGHT ...)

eg: 例如:

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; }
   [***Call some function here***]

   public string blabla{get;set;}
}

Or maybe another idea? 还是另一个想法?

This can be done by imlementing a custom validation attribute check this link and this 这可以通过imlementing自定义验证完成属性检查此链接

Example: 例:

public sealed class DateEndAttribute : ValidationAttribute
{
    public string DateStart { get; set; }

    public override bool IsValid(object value)
    {
        // Get value of datestart property
        string dateStartString = HttpContext.Current.Request[DateStart];
        DateTime dateEnd = (DateTime)value;
        DateTime dateStart = DateTime.Parse(dateStartString);

        // Start must be before end
        return dateStart <= dateEnd;
    }

    public override string FormatErrorMessage(string name)
    {
        return name + " has to be after startdate";
    }
}

Usage: 用法:

    [Required]
    [Display(Name = "StartDate")]
    public DateTime StartDate { get; set; }

    [Display(Name = "EndDate")]
    [DateEnd(DateStart = "StartDate")]
    public DateTime EndDate { get; set; }

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

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