在你的模型类中添加数据注解,使用[MaxLength]属性来设置最大长度,并使用[Required(ErrorMessage=" ")]属性来设置验证消息。
例如,如果你有一个名为"Person"的模型类,其中有一个名为"Name"的字符串属性,你可以这样写:
public class Person { [Required(ErrorMessage = "Please enter a name.")] [MaxLength(50, ErrorMessage = "The name cannot exceed 50 characters.")] public string Name { get; set; } }
这将确保当用户尝试提交一个超过50个字符的名字时,在表单上会显示一个验证消息“姓名不能超过50个字符”。如果用户没有输入名字,则会显示另一个消息“请填写姓名”。