[英]Client Side Validation Not working for custom Attribute
嗨,我有一個自定義屬性
public class NameAttribute : RegularExpressionAttribute
{
public NameAttribute() : base("abc*") { }
}
這適用於服務器端,但不適用於客戶端,但這樣
[RegularExpressionAttribute("abc*",ErrorMessage="asdasd")]
public String LastName { get; set; }
適用於兩者。 我看了這個,但它沒有幫助。
我非常感謝你的幫助。
謝謝
您可能需要在Application_Start
注冊與此自定義屬性關聯的DataAnnotationsModelValidatorProvider
:
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
注冊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.