我正在使用示例asp.net mvc应用程序,我想在某些文本框上添加特定验证
如:
我将如何做到这一点?
答案 0 :(得分:6)
示例:
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Company company)
{
//validate and save data
if (ValidateCompanyData(company))
{
_service.SaveCompanyData(CustomerId, company);
ViewData["info"] = "Your changes have been saved.";
}
var companyViewData = GenerateCompanyViewData(company);
return View("Index", companyViewData);
}
[NonAction]
public bool ValidateCompanyData(Company company)
{
if (!company.VAT.HasValue())
{
ModelState.AddModelError("VAT", "'Vat' is a required field.");
}
if (!company.CompanyName.HasValue())
{
ModelState.AddModelError("CompanyName", "'Name' is a required field.");
}
return ModelState.IsValid;
}
查看:
Html.ValidationMessage("VAT")
访问错误消息。
如果你想知道: .HasValue()是一个扩展方法,与!string.IsNullorEmpty()
相同