GetClientValidationRules is never called in MVC application

穿精又带淫゛_ 提交于 2021-01-22 19:51:45

问题


I have a custom ValidationAttribute that implements IClientValidatable. But the GetClientValidationRules is never called to actually output the validation rules to the client side.

There is nothing special about the attribute but for some reason it is never called. I've tried registering an adapter in Application_Start() but that also doesnt work.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class CustomAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return true;
    }
    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string errorMessage = FormatErrorMessage(metadata.GetDisplayName());

        yield return new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = "custom" };
    }

    #endregion
}

public class CustomAdapter : DataAnnotationsModelValidator<CustomAttribute>
{
    public CustomAdapter(ModelMetadata metadata, ControllerContext context, CustomAttribute attribute)
        : base(metadata, context, attribute)
    {
    }
    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return this.Attribute.GetClientValidationRules(this.Metadata, this.ControllerContext);
    }
}

In Application_Start() I have:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomAttribute), typeof(CustomAdapter));

When I put a breakpoint inside GetClientValidationRules it is never hit.


回答1:


In order GetClientValidationRules() method to get called you must enable client-side validation support. It can be done in the following ways:

In the web.config (for all pages of application):

<appSettings>
    <add key="ClientValidationEnabled" value="true" />

Or on particular view only:

either

@{ Html.EnableClientValidation(); }

or

@(ViewContext.ClientValidationEnabled = true)

Please note it must go before

@using (Html.BeginForm())

statement.

If you are using jquery unobtrusive validation (which seems to be a standard currently), you'll also need to enable it:

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

in web.config or

@Html.EnableUnobtrusiveJavaScript()

for particular views.



来源:https://stackoverflow.com/questions/24375967/getclientvalidationrules-is-never-called-in-mvc-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!