服务器和客户端验证差异增加了额外的跨度

server and client side validation differences adding extra span

我在服务器端和客户端都有验证 当在服务器端添加验证时,我得到的结构与在客户端进行时不同

客户

<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")
}

不确定为什么会出现问题。

但这里是生成额外跨度的代码。代码在 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());
    }

    ...

}

希望对您有所帮助!