您可能需要在以下位置注册DataAnnotationsModelValidatorProvider
关联到此自定义属性Application_Start
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)
);
}
您还可以查看以下博客文章。
这是我用来测试的完整示例。
模型:
public class NameAttribute : RegularExpressionAttribute
{
public NameAttribute() : base("abc*") { }
}
public class MyViewModel
{
[Name(ErrorMessage = "asdasd")]
public string LastName { get; set; }
}
控制器:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
}
return View(model);
}
}
看法:
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcValidation.js") %>"></script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(x => x.LastName) %>
<%= Html.EditorFor(x => x.LastName) %>
<%= Html.ValidationMessageFor(x => x.LastName) %>
<input type="submit" value="OK" />
<% } %>
加上Application_Start
我之前展示的注册。