ASP.NET Core MVC 6 jQuery Validation not working on AJAX Post

333 Views Asked by At

I am dynamically creating create/update form on a bootstrap popup model using AJAX. When a user clicks, add or edit, a model will be visible with the create/update form. I want to do a jQuery validation when user clicks submit. If a form is valid, then it would perform AJAX post.

The jQuery ("#userForm").valid() is always returning true, even if the required fields condition is not satisfied. What am I missing?

My view looks like this

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

My view model looks like this

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; }
}

My jQuery method looks like this

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');
            }
        })
    });
}

I have referenced jQuery validation and unobtrusive validation as

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}
0

There are 0 best solutions below