我已经创建了一个自定义数据注释来对我的视图模型进行一些验证.问题是它没有在客户端验证.这是我的模特:
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; });