We help IT Professionals succeed at work.

ASP.NET MVC - Help with posting form using jqueryval and AjAX

Sarah Ward
Sarah Ward asked
on
261 Views
Last Modified: 2018-02-02
I have an ASP.NET MVC form that I'm trying to validate using JQueryVal.   The API controller works as I've tested in Postman successfully.  My problem is this.

The field validators work, however when the form IS valid it does not POST to the API and create a new record in my database table.

Instead it redirects you to the same page with the Form data in the querystring as parameters.

Here's my View that includes my AjAX/Jquery script.

@model ClienteManagment.ViewModels.IntakeFormViewModel

@{
    ViewBag.Title = "IntakeForm";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<h2>Intake Form</h2>

<form id="newIntake">

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.ItemName)
        @Html.TextBoxFor(m => m.Intake.ItemName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.ItemName)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.ItemDescription)
        @Html.TextBoxFor(m => m.Intake.ItemDescription, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.ItemDescription)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.Segment)
        @Html.DropDownListFor(m => m.Intake.SegmentId, new SelectList(Model.Segment, "Id", "Name"), "Select Segment", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.SegmentId)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.MarketingLead)
        @Html.DropDownListFor(m => m.Intake.MarketingLeadId, new SelectList(Model.MarketingLead, "Id", "Name"), "Select Marketing Lead", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.MarketingLead)
    </div>

    <div class="form-group">
        @Html.Label("Intake Type")
        <br />
        <div class="radio">
            @{
                foreach (var row in Model.IntakeType)
                {
                    @Html.RadioButtonFor(m => m.Intake.IntakeTypeId, row.Id)
                    @Html.Label(row.Name)
                    <br />
                }
            }
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.Quantity)
        @Html.TextBoxFor(m => m.Intake.Quantity, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.Quantity)
    </div>

    <button class="btn btn-primary">Submit</button>
</form>

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
    <script>

        $(document).ready(function () {
            var validator = $("#newIntake").validate({
                submitHandler: function () {

                    console.log("Handling Submit!");

                    var dateSub = new Date().toLocaleString();

                    var formData = {
                        "ItemName": $("#Intake_ItemName").val(),
                        "ItemDescription": $("#Intake_ItemDescription").val(),
                        "IntakeTypeId": $("#Intake_IntakeTypeId").val(),
                        "SegmentId": $("#Intake_SegmentId").val(),
                        "MarketingLeadID": $("#Intake_MarketingLeadId").val(),
                        "Quantity": $("#Intake_Quantity").val(),
                        "DateSubmitted": dateSub
                    };

                    $.ajax({
                        url: "/api/intake",
                        method: "post",
                        data: formData
                    })
                        .done(function () {
                            console.log("Yeah!  It worked.");
                            // Clear the form
                            //$("#newIntake").get(0).reset()
                            //validator.resetForm();
                        })
                        .fail(function () {
                            console.log("Something unexpected happened.");
                        });

                    return false;
                }
            });
        });

    </script>
}

Open in new window

Comment
Watch Question

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
add this after line 69 to prevent any submission :
$(":button.btn.btn-primary").click(function(e) {
     e.preventDefault();
});

Open in new window

Sarah WardDeveloper

Author

Commented:
Thanks for your response, Leakim971, however I'm not trying to prevent a submission.  

Just to be clear, my field validators work as I want them to.  My problem is this.  When the form IS valid and I click the submit button it does not POST to the API and create a new record in my database table.  

How can I get the submit button to post when all my fields are valid?
Sarah WardDeveloper

Author

Commented:
UPDATE:  I moved my code OUTSIDE of the $(document).ready function (See code snippet below).  Now if I click the SUBMIT button it causes a POST and the form data is sent to the database and creates the new record.

However by moving the code outside the $(document).ready function Validation no longer works.

I need to validate the form, and if it is valid, post the Form's data to the database.

Please help.

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
    <script>

        // MOVED CODE OUTSIDE $(document).ready
        $(document).ready(function () {
            // CODE USED TO BE HERE
        });

        // NOW CODE IS HERE...
        var validator = $("#newIntake").validate({
            submitHandler: function () {

                console.log("Handling Submit!");

                var dateSub = new Date().toLocaleString();

                var formData = {
                    "ItemName": $("#Intake_ItemName").val(),
                    "ItemDescription": $("#Intake_ItemDescription").val(),
                    "IntakeTypeId": $("#Intake_IntakeTypeId").val(),
                    "SegmentId": $("#Intake_SegmentId").val(),
                    "MarketingLeadID": $("#Intake_MarketingLeadId").val(),
                    "Quantity": $("#Intake_Quantity").val(),
                    "DateSubmitted": dateSub
                };

                $.ajax({
                    url: "/api/intake",
                    method: "post",
                    data: formData
                })
                    .done(function () {
                        console.log("Yeah!  It worked.");
                        // Clear the form
                        validator.resetForm();
                    })
                    .fail(function () {
                        console.log("Something unexpected happened.");
                    });

                return false;
            }
        });

</script>

}

Open in new window

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
from your last code snippet what is the goal of the lines 29 to 41 ?
Sarah WardDeveloper

Author

Commented:
Line 29 - I'm using an AjAX call to my RESTful API Controller to POST the data in the Form

Line 34 - If it successfully performs the POST (.done) then, I reset my form to blank values. (I also, for troubleshooting purposes only, do a console.log showing that it was successful)

Line 39 - If it fails (.fail) again, for troubleshooting purposes I note it in the console.log.

I hope this helps.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
so, you post your form data with ajax, why do you want to let the page submit the data too ?
Sarah WardDeveloper

Author

Commented:
I really just want to post the form data using AJAX, but maybe my code isn't written correctly to do that.  That's where I'm stuck.

My goal for the page is:

1.) OnClick of the Submit button Validate the form fields using jqueryval
2.) If the Form is not validate highlight the fields that need to be addresses and allow the user to make corrections.
2.) If the Form passes the validation I want to POST that data using AJAX only to my RESTful API Controller and than reset the form, clearing all the previously entered values.

What do I need to alter in my code to make this work?
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
So back to my first answer. You must prevent page submit.
Once your validation is OK, you redirection user to success/next page in your done Ajax callback.
Sarah WardDeveloper

Author

Commented:
I've added your code.   Here's what happens:

- If the form is blank and I hit the button:  No validation notifications.
- If I partially fill out the form, leaving some of the required fields blank and hit the button:  Again, no validation and no notifications.
- If I fill out the form completely with all valid entries and hit the button.  Nothing happens.  No POST.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Ok, could you share a link to see your page un live ?
Sarah WardDeveloper

Author

Commented:
I'm testing this using localhost so I'm not able to do that.   I may be able to provide a link for you tomorrow when I have access to a server.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Ok so place an alert inside your validation block, just before the Ajax call.

alert("reached");

Let me know if it run the alert
Sarah WardDeveloper

Author

Commented:
I placed your code as directed.  Filled out the form with valid entries and clicked submit.  The alert never fired.

My code is below:

@section scripts
{
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(document).ready(function () {
            var validator = $("#newIntake").validate({
                submitHandler: function () {

                    console.log("Handling Submit!");

                    var dateSub = new Date().toLocaleString();

                    var formData = {
                        "ItemName": $("#Intake_ItemName").val(),
                        "ItemDescription": $("#Intake_ItemDescription").val(),
                        "IntakeTypeId": $("#Intake_IntakeTypeId").val(),
                        "SegmentId": $("#Intake_SegmentId").val(),
                        "MarketingLeadID": $("#Intake_MarketingLeadId").val(),
                        "Quantity": $("#Intake_Quantity").val(),
                        "DateSubmitted": dateSub
                    };

                    alert("reached");

                    $.ajax({
                        url: "/api/intake",
                        method: "post",
                        data: formData
                    })
                        .done(function () {
                            console.log("Yeah!  It worked.");
                            // Clear the form
                            validator.resetForm();
                        })
                        .fail(function () {
                            console.log("Something unexpected happened.");
                        });

                    return false;
                }
            });
        });

</script>

}

Open in new window

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
I believe you don't see anything in the console toi(Line 9).
You probably have a JS error before in your page...
Maybe try to replace :
$("#newIntake")
By :$("#<%=newIntake.ClientID %>")
Developer
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Sarah WardDeveloper

Author

Commented:
Thanks for your help!
Sarah WardDeveloper

Author

Commented:
I got it working!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.