[英]Asp.net MVC model validating
我是Asp.net Mvc的新手(4)
我可以調用一個函數來驗證模型屬性嗎(超過了REQUIRED,MAXLENGHT ...)
例如:
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;}
}
還是另一個想法?
這可以通過imlementing自定義驗證完成屬性檢查此鏈接和此
例:
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";
}
}
用法:
[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.