使用ajax进行客户端验证不起作用

时间:2018-06-05 17:13:31

标签: javascript c# asp.net-mvc validation

我正在尝试在ajax表单上实现客户端验证并遇到问题。我按照指南和文章,但没有任何作用。当我输入无效数据时,不会出现错误。 以下是应该进行验证的部分视图之一

@model JustBlog.Models.Admin.TagEditViewModel

@{
    ViewBag.Title = "Edit tag";
    //Layout = "~/Views/Shared/_AdminLayout.cshtml";
    Layout = null;
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

<div class="modal-header">
    <h5 class="modal-title" id="exampleModalLongTitle">Редактирование тега</h5>
    <button type="button" class="close" aria-label="Close" id="btnClose1">
        <span aria-hidden="true">&times;</span>
    </button>
</div>


<div class="modal-body">
    @using (Html.BeginForm("EditTag", "Tag", FormMethod.Post, new { id = "submittedForm" }))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(m => m.Tag.Id)

        <div class="form-group">
            @Html.LabelFor(m => m.Tag.Name, new { @class = "control-label col-md-6" })
            <div class="col-12">
                @Html.EditorFor(m => m.Tag.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(m => m.Tag.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">

            @Html.LabelFor(m => m.Tag.UrlSlug, new { @class = "control-label col-md-6" })
            <div class="col-12 input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="example-url">https://example.com/tags/</span>
                </div>
                @Html.EditorFor(m => m.Tag.UrlSlug, new { htmlAttributes = new { @class = "form-control", id = "example-url", aria_describedby = "example-url" } })
                @Html.ValidationMessageFor(m => m.Tag.UrlSlug, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.Tag.Description, new { @class = "control-label col-md-6" })
            <div class="col-12">
                @Html.EditorFor(m => m.Tag.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(m => m.Tag.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @if (Model.IncludePosts)
            {
                <p>
                    <button class="btn btn-primary ml-2" id="btnShowPosts" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                        Show related posts
                    </button>
                </p>
                <div class="collapse" id="collapseExample">
                    <div class="card card-body" id="postsTarget">
                    </div>
                </div>
            }
            else
            {
                <p>
                    <button class="btn btn-primary ml-2" type="button">
                        No related posts
                    </button>
                </p>
            }
        </div>

        <div class="modal-footer">
            <input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
            <button type="button" class="btn btn-secondary closefirstmodal" id="btnClose2">Close</button>
        </div>
    }
</div>

@Scripts.Render("~/bundles/jqueryval")

<script>
    var _getRalatedPosts = '@Url.Action("PostsForTag", "Tag", new { id = Model.Tag.Id })';
    var _postsForTag = '@Url.Action("PostsForTag", "Tag", new { id = Model.Tag.Id })';
    var _successedTags = '@Url.Action("GetTagsData", "Tag")';

</script>

@Scripts.Render(Url.Content("~/Scripts/Assets/Tag/EditTag/pageTagControl.js"));

首先,我渲染jqueryval包。然后一些初始化一些值并渲染第二个脚本。 这就是捆绑的实施方式:

bundles.Add(new ScriptBundle("~/bundles/jqueryval")
                .Include("~/Scripts/jquery.validate*",
                "~/Scripts/jquery.validate.unobtrusive*"));

jQuery(v3.3.1)和jquery.unobtrusive-ajax.js加载布局。

这是JS文件代码的一部分:

 $(function (){
 $("#submittedForm").submit(function (e) {
    clickedOnce = true;
    e.preventDefault();

    console.log($("#submittedForm"));
    var _form = $("#submittedForm")
        .removeData("validator") 
        .removeData("unobtrusiveValidation");
    var _formValue = $(this)[0];

    $.validator.unobtrusive.parse(_form);
    _form.validate();

    //isValid is ALWAYS true !
    var isValid = _form.valid();

    if (isValid) {
        let _data = new FormData(_formValue);

        $.ajax({
            method: "POST",
            processData: false,
            cache: false,
            contentType: false,
            url: _postEditTag,
            data: _data,
            success: function (response) {
               //other code
            },
            error: function (jqXHR) {
                //other code
            }
        })
            .done(function (data, textStatus, jqXHR) {
                //and other one!
            });
    }
});
 })

单击ajax动作后,此视图将显示为模态。 这是ajax选项和onFunctions:

@Ajax.ActionLink(item.Name, "Admin", new AjaxOptions
            {
                Url = Url.RouteUrl(new { controller = "Tag", action = "EditTag", id = item.Id }),
                HttpMethod = "GET",
                OnBegin = "IsLoading",
                OnSuccess = "SetContent",
                OnFailure = "AlertUser",
                OnComplete = "SetValidation"
            })
<scripts>
function SetValidation() {
    $('#submittedForm').removeData('validator');
    $('#submittedForm').removeData('unobtrusiveValidation');
    $("#submittedForm").each(function () { $.data($(this)[0], 'validator', false); });
    $.validator.unobtrusive.parse("#submittedForm");
}
</scripts>

我错过了什么?我甚至重新安装了jQuery / jQuery.validation包。 希望你提前帮助我!

0 个答案:

没有答案