Avatar of Sarah Ward
Sarah WardFlag for United States of America asked on

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

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

ASP.NETjQueryAJAX

Avatar of undefined
Last Comment
Sarah Ward

8/22/2022 - Mon
leakim971

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

Open in new window

ASKER
Sarah Ward

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?
ASKER
Sarah Ward

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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
leakim971

from your last code snippet what is the goal of the lines 29 to 41 ?
ASKER
Sarah Ward

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.
leakim971

so, you post your form data with ajax, why do you want to let the page submit the data too ?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Sarah Ward

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?
leakim971

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.
ASKER
Sarah Ward

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.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
leakim971

Ok, could you share a link to see your page un live ?
ASKER
Sarah Ward

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.
leakim971

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

alert("reached");

Let me know if it run the alert
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Sarah Ward

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

leakim971

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 %>")
ASKER CERTIFIED SOLUTION
Sarah Ward

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Sarah Ward

Thanks for your help!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
Sarah Ward

I got it working!