当没有数据发布时,在页面加载时显示MVC Razorvalidation错误
我正在搞乱数据注释。 当我单击链接转到页面时,将显示validation消息,但我希望validation消息不显示,除非已发布数据。
视图:
@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" }) @Html.ValidationSummary(true, "Registration Failed. Check your credentials") @Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")
模型:
[Required(ErrorMessage = "Email is required")] [DataType(DataType.EmailAddress)] [EmailAddress] [Display(Name = "Email Address: ")] public string EmailAddress { get; set; }
控制器:
[HttpGet] public ActionResult AddUser() { return View(); } [HttpPost] public ActionResult AddUser(UserCreateViewModel user) { if (ModelState.IsValid) { var success = UserRepository.AddUser(user); if (success) { return View("Success"); } } return View("AddUser"); }
就像我说的,我的问题出现在AddUser视图的页面加载上。 当我单击链接以查看AddUser页面时,validation消息在加载后显示,但此时没有数据已发布且模型为空。
将validation样式设置为:
.validation-summary-valid { display:none; }
所以默认情况下它是隐藏的。 错误将触发它显示。
绑定用户后可以清除模型状态:
ModelState.Clear();
这是因为ModelBinder
将在绑定时设置ModelState
。 在绑定模型并返回具有相同模型的视图的每个操作中,您都会遇到此问题。
[HttpPost] public ActionResult AddUser(UserCreateViewModel user) { if (ModelState.IsValid) { var success = UserRepository.AddUser(user); if (success) { return View("Success"); } } ModelState.Clear(); // <------- return View("AddUser"); }
.field-validation-valid { display: none; }
每当validation在页面加载时触发时,此“.field-validation-valid”值将自动添加到触发的输入元素的class属性中。
通过添加CSS来显示none作为特定类的值,您将不再在初始页面加载时看到validation消息。
在触摸特定输入元素后,validation消息仍将正常显示。
这种情况发生在我身上时,模型没有传递给视图,并且get和post都使用了相同的动作。
我申请了@Renan Araujo的解决方案
$('.field-validation-error').html("");
上述就是C#学习教程:当没有数据发布时,在页面加载时显示MVC Razorvalidation错误分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1034405.html