这是一个Model:
[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 8)]
public string UserName { get; set; }
在UI层验证:
UserName:@Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName)
or
UserName:<input type="text" name="UserName" /> @Html.ValidationMessageFor(m => m.UserName)
在控制器中也可以这样验证:
[HttpPost]
public ActionResult Index(User model)
{
string aa = "true";
if (!ModelState.IsValid)
{
aa = "false";
}
Response.Write(aa);
return View();
}
通过json为什么每个model验证:
[Remote(“CheckUserName”)]
public string UserName { get; set; }
然后在AccountController里指定一个CheckUserName方法:
public JsonResult CheckUserName(string username)
{
var result = Membership.FindUsersByName(username).Count == 0;
return Json(result, JsonRequestBehavior.AllowGet);
}