您可能需要登記Application_Start
關聯到這個自定義屬性DataAnnotationsModelValidatorProvider
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)
);
}
您還可以檢出following blog post。
這裏是我用來測試這個完整的例子。
型號:
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
註冊我之前展示。
感謝您的帖子。我希望我能給你更多的不只一分 – David 2011-04-17 18:53:24