ASP.NET Core MVC 6 jQuery 验证不适用于 AJAX Post

问题描述 投票:0回答:0

我正在使用 AJAX 在引导弹出模型上动态创建创建/更新表单。当用户单击、添加或编辑时,模型将与创建/更新表单一起显示。我想在用户单击提交时进行 jQuery 验证。如果表单有效,那么它将执行 AJAX post。

jQuery

("#userForm").valid()
总是返回 true,即使不满足必填字段条件。我错过了什么?

我的观点是这样的

@using (Html.BeginForm("SaveData", "Home", FormMethod.Post, new { id = "userForm", name = "userForm"}))
 {
    @Html.AntiForgeryToken()
    <div class="modal-body">
        <div class="col-12">
            <label class="form-check-label" for="Name">Name*</label>
            @Html.TextBoxFor(m => m.Name, new { @id = "txtName", @class = "form-control", @placeholder = "Name"})
             @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })              
        </div>
        <div class="col-12  mt-5">
            <label class="form-check-label" for="Description">More Info</label>
            @Html.TextAreaFor(m => m.Description, new { @style = "width: 100%; height: 200px;",@class="form-control" })
          
        </div>
        </div>
    <div class="modal-footer">
        <div class="col-sm-8 col-md-8 col-lg-8 text-center">
            <input class="btn btn-primary" type="button" value="Save" id="btnSubmit" onclick="saveData()" />
                <input class="btn btn-primary" type="button" value="Cancel" id="btnCancel"/>
            </div>                
        </div>
       
        @Html.HiddenFor(Model=>Model.Id,new { @id = "pId"})
    }

我的视图模型看起来像这样

public class DataEntryViewModel
{
        public int Id{get;set;}
        [Required, Remote("NameAlreadyExists", "Home", AdditionalFields = "Id", ErrorMessage = "Name already exists.")]
        public string Name { get; set; } //Name is unique
      
        public string Description { get; set; }
}

我的 jQuery 方法看起来像这样

function saveData()
{
    if ($("#userForm").valid()) { //check if form is valid using model annotation
        
        $('#userForm').submit();
    }
    else {
       
        return false;
    }

    $("#userForm").on("submit", function (event) {
        event.preventDefault();
        $('#btnSubmit').attr('disabled', 'disabled');
        var url = $(this).attr("action");
        var formData = $(this).serialize();
        $.ajax({
            url: url,
            type: "POST",
            data: formData,
            dataType: "json",
            success: function (response) {
                alert('Success! ' + JSON.stringify(response));
            },
            error: function (response) {
                alert('Error!');
            },
            complete: function () {
                $('#btnSubmit').removeAttr('disabled');
            }
        })
    });
}

我将 jQuery 验证和不显眼的验证引用为

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}
asp.net-core-mvc asp.net-ajax jquery-ajax
© www.soinside.com 2019 - 2024. All rights reserved.