问题
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