如何解决使用Asp.net Core MVC Bootstrap 4,我无法正确解决服务器端添加的模型状态错误
一切似乎都可以与视图模型上的验证注释一起使用。但是,当在服务器端(在表单发布后)进行一些其他验证并添加modelstate错误时,我遇到了问题。这些错误实际上会适当地呈现并通过服务器的响应来传递,但是,与表单上的属性/输入之一相关的错误最终被清除了。现在,如果我将验证摘要放在页面上,则消息确实显示在那里,但是与输入直接相关的消息不再显示,并且输入也不再标记为无效。对可能发生的事情有任何想法吗?
我正在使用jQuery v2.1.4,jQuery验证v1.14.0,jQuery验证不干扰v3.2.6,Bootstrap 4.4.1,并且我正在使用此插件的v2.2.0版本:https://github.com/brecons/jquery-validation-unobtrusive-bootstrap。在找到我刚刚提到的插件之前,我无法使任何BS4验证工作正常/看起来正确。现在它可以正常工作并且看起来不错,但是服务器端添加的modelstate错误不会像我想要的那样最终传递给客户端。而且我认为它们可以在响应中从服务器到达客户端,但是我认为可能有一些脚本处理正在清除这些错误消息。我认为现在已经有人解决了这个问题。
cshtml设置:
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" type="email" autocomplete="off" autofocus="true" />
_<span asp-validation-for="Email" class="invalid-feedback"></span>_
</div>
the server-side add model error statement:
this.ModelState.AddModelError(nameof(LoginViewModel.Email),"Your account has been disabled.");
从服务器到客户端的响应:
<div class="form-group">
<label class="control-label" for="Email">Email Address</label>
<input class="form-control input-validation-error" type="email" autocomplete="off" autofocus="true" data-val="true" data-val-required="The Email Address field is required." id="Email" name="Email" value="disabled@rew.com" />
_<span class="invalid-feedback field-validation-error" data-valmsg-for="Email" data-valmsg-replace="true">Your account has been disabled.</span>_
</div>
这是从页面在浏览器中显示后对页面的检查得出的。如您所见,来自服务器的验证消息已消失,输入中的错误已清除:
<div class="form-group">
<label class="control-label" for="Email">Email Address</label>
<input class="form-control input-validation-error is-valid" type="email" autocomplete="off" autofocus="true" data-val="true" data-val-required="The Email Address field is required." id="Email" name="Email" value="disabled@rew.com" style="" aria-required="true" aria-invalid="false" aria-describedby="Email-error">
<div id="Email-error" class="is-invalid invalid-feedback" style="display: block;"></div>
_<span class="invalid-feedback field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>_
</div>
解决方法
您需要添加自定义 css 才能正常工作
.field-validation-error { color:red; font-size: smaller; }
.input-validation-error{ border-color: #dc3545; }
因为dotnet MVC中的validation-for在渲染的html中使用了这个类:
<span class="field-validation-error" data-valmsg-for="Customer.Name" data-valmsg-replace="true">The Name field is required.</span>
<input class="input-validation-error form-control" data-val="true" data-val-length="The field Name must be a string with a maximum length of 255." data-val-length-max="255" data-val-required="The Name field is required." id="Customer_Name" maxlength="255" name="Customer.Name" type="text" value="">
感谢此博客: https://dotnetthoughts.net/how-to-use-bootstrap-style-validation-in-aspnet-core/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。