System.ComponentModel.DataAnnotations
System.ComponentModel.DataAnnotations
1.Create Model (Code First)
2.Create Controller
3.Auto create view
4. add Script on below Create.html
5.add Attribute in Model
(1) Compare
(2)CustomValidation <Server>
1.) create new class for CustomValidation
public class QualifiedAgeAttribute : ValidationAttribute
{
// Fields
private int _qualifiedAge;
// Constructors
public QualifiedAgeAttribute(int qualifiedAge)
{
this._qualifiedAge = qualifiedAge;
}
// Methods
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime birthday = (DateTime)value;
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year - 1;
if (age >= _qualifiedAge)
{
// valid
return ValidationResult.Success;
}
else
{
// invalid
var errorMsg = string.Format("Your age({0}) should be over {1}", age, _qualifiedAge);
return new ValidationResult(errorMsg);
}
}
}
2.) add Attribute
(3.)Display
(4.)MaxLength & MinLength
(5.)Range
(6.)RegluarExpression
(7.)Require
(8.)Remote <using System.Web.Mvc , Javascript>
1.) add Action in Controller
2.) add Attribute -> [ Remote("ActionName", "ControllerName") ]
(9.)DataType
參考書籍,網址: MVC5開發美學 、 小菜鳥