1

嗨,我有一个自定义属性

 public class NameAttribute : RegularExpressionAttribute
 {
     public NameAttribute() : base("abc*") { }
 }

这适用于服务器端,但不适用于客户端,但这

[RegularExpressionAttribute("abc*",ErrorMessage="asdasd")]
public String LastName { get; set; }

适用于两者。我读了这个,但它没有帮助。

我非常感谢您的帮助。

谢谢

4

1 回答 1

4

您可能需要在以下位置注册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我之前展示的注册。

于 2011-04-17T15:00:21.470 回答