C# 客户端自定义数据批注验证

C# 客户端自定义数据批注验证,c#,asp.net,asp.net-mvc,asp.net-mvc-3,razor,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 3,Razor,我已经创建了一个自定义数据注释来对视图模型进行验证。问题是它不能在客户端进行验证。这是我的模型: public class MemberViewModel { [ScaffoldColumn(false)] public int MemberId { get; set; } [Required(ErrorMessage = "Name is required")] public string Name { get; set; } //My custom

我已经创建了一个自定义数据注释来对视图模型进行验证。问题是它不能在客户端进行验证。这是我的模型:

public class MemberViewModel
{
    [ScaffoldColumn(false)]
    public int MemberId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    //My custom data annotation
    [EnforceTrue(ErrorMessage = "You must agree to the Terms and Conditions")]
    public bool AgreeTerms { get; set; }
}
我的数据批注验证代码:

public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
    public EnforceTrueAttribute() { }

    public override bool IsValid(object value)
    {
        return value != null && (bool)value == true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule() { ValidationType = "enforcetrue", ErrorMessage = this.ErrorMessageString };
    }
}
我的看法是:

@using (Html.BeginForm("Index", "Members", FormMethod.Post)) {

    @Html.HiddenFor(m => m.MemberId)

    <div class="editor-label">@Html.LabelFor(model => model.Name)</div>
    <div class="editor-field">@Html.TextBoxFor(model => model.Name)</div>

    <div class="editor-field">@Html.CheckBoxFor(model => model.AgreeTerms) <label for="AgreeTerms">I agree to the Terms and Conditions</label></div>

    <p>
        <input type="submit" value="Submit" />
    </p>

    @Html.ValidationSummary()
}
@使用(Html.BeginForm(“Index”,“Members”,FormMethod.Post)){
@Html.HiddenFor(m=>m.MemberId)
@LabelFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Name)
@我同意这些条款和条件

@Html.ValidationSummary() }
因此,所有其他错误消息都会显示在带有客户端验证的验证摘要中。但是对于我的自定义数据注释,直到模型的其余部分有效,并且在您提交表单并重新加载页面之后,错误消息才会显示在摘要中

我是否需要在这里做些其他的事情来让它与其他错误一起显示在摘要中


我正在使用C#和ASP.NET MVC 3实现IClientValidable,它只会向生成的html输入添加不引人注目的属性。要在客户端启用验证,您必须编写使用这些不引人注目的属性来验证输入的验证器。您可以在asp.net mvc 3中找到关于客户端和服务器验证的非常好的解释。mvc 3最近也有同样的问题。你可以写:

$.validator.addMethod('enforcetrue', function (value, element) {
    return $(element).is(":checked");
});
$.validator.unobtrusive.adapters.add('enforcetrue', [], function (options) {
    options.messages['enforcetrue'] = options.message;
    options.rules['enforcetrue'] = options.params;
});

这里有一个类似的问题

远程验证器是您需要的,这里是链接

$.validator.addMethod('enforcetrue', function (value, element) {
    return $(element).is(":checked");
});
$.validator.unobtrusive.adapters.add('enforcetrue', [], function (options) {
    options.messages['enforcetrue'] = options.message;
    options.rules['enforcetrue'] = options.params;
});