加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 客户端自定义数据注释验证

发布时间:2020-12-15 06:36:29 所属栏目:百科 来源:网络整理
导读:我已经创建了一个自定义数据注释来对我的视图模型进行一些验证.问题是它没有在客户端验证.这是我的模特: public class MemberViewModel{ [ScaffoldColumn(false)] public int MemberId { get; set; } [Required(ErrorMessage = "Name is required")] public
我已经创建了一个自定义数据注释来对我的视图模型进行一些验证.问题是它没有在客户端验证.这是我的模特:
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 };
    }
}

我的控制器方法:

[HttpPost]
public ActionResult Index(MemberViewModel viewModel)
{
    Member member = new Member();
    TryUpdateModel(member);

    if (ModelState.IsValid)
    {
        _membersRepository.SaveMember(member);

        return RedirectToAction("Index","Home");       
    }

    return View(viewModel);     // validation error,so redisplay same view            
}

我的观点是:

@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()
}

所以我的所有其他错误消息都会在客户端验证的验证摘要中显示出来.但是对于我的自定义数据注释,错误消息在模型的其余部分有效之前不会显示,并且在您提交表单和页面重新加载之后,错误显示在摘要中.

我还需要做些什么来让它在其他错误的摘要中显示出来吗?

我正在使用C#和ASP.NET 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;
});

类似的问题在这里ASP.NET MVC 3 client-side validation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读