1

こんにちは、私はカスタム属性を持っています

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

これはサーバー側では機能しますが、クライアント側では機能しませんが、

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

両方で動作します。私はこれを読みましたが、役に立ちません。

よろしくお願いいたします。

ありがとうございました

4

1 に答える 1

4

You might need to register a DataAnnotationsModelValidatorProvider associated to this custom attribute in Application_Start:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)
    );
}

You might also checkout the following blog post.

And here's the full example I used to test this.

Model:

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

public class MyViewModel
{
    [Name(ErrorMessage = "asdasd")]
    public string LastName { get; set; }
}

Controller:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

        }
        return View(model);
    }
}

View:

<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" />
<% } %>

Plus the Application_Start registration I showed earlier.

于 2011-04-17T15:00:21.470 に答える