我在服务器端和客户端都进行了验证 当在服务器端添加验证时,我得到的结构与我在客户端进行验证时的结构不同
客户端
<span data-valmsg-replace="true" data-valmsg-for="Location" class="text-danger field-validation-error"><span for="Location" class="">The Location field is required.</span></span>
服务器端
<span data-valmsg-replace="true" data-valmsg-for="Location" class="field-validation-error text-danger">Broken</span>
问题是
<span for="Location" class="">
他们是否有办法让服务器端验证添加额外的跨度? 或者他们是否可以通过客户端验证来消除额外的跨度?
任何帮助表示赞赏:)
模型
public class LocationModel
{
[Required]
public int Id { get; set; }
[Required]
public string Location { get; set; }
}
控制器
[HttpPost]
public ActionResult LocationView(LocationModel lm)
{
ModelState.AddModelError("Location", "Broken");
return View();
}
查看
@model WebApplication1.Models.LocationModel
@{
ViewBag.Title = "View";
}
<h2>View</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>LocationModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
答案 0 :(得分:1)
不确定为什么会出现问题。
但是这里是生成额外跨度的代码。代码在jquery.validate.js。
showLabel: function( element, message ) {
...
} else {
// create error element
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
...
},
errorElement的默认值是 label ,但jquery.validate.unobtrusive.js将其更改为 span 。 有几种方法可以改变这种行为。
但是这里有一个,改变jquery.validation.unobtrusive.js
从:
function onError(error, inputElement) { // 'this' is the form element
...
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
...
}
要:
function onError(error, inputElement) { // 'this' is the form element
...
if (replace) {
container.empty().html(error.html());
}
...
}
希望这有帮助!