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

Lynn CurtDeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Open in new window

0
 
Lynn CurtDeveloperAuthor 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?
0
 
Lynn CurtDeveloperAuthor 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

0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
leakim971PluritechnicianCommented:
from your last code snippet what is the goal of the lines 29 to 41 ?
0
 
Lynn CurtDeveloperAuthor 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.
0
 
leakim971PluritechnicianCommented:
so, you post your form data with ajax, why do you want to let the page submit the data too ?
0
 
Lynn CurtDeveloperAuthor 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?
0
 
leakim971PluritechnicianCommented:
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.
0
 
Lynn CurtDeveloperAuthor 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.
0
 
leakim971PluritechnicianCommented:
Ok, could you share a link to see your page un live ?
0
 
Lynn CurtDeveloperAuthor 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.
0
 
leakim971PluritechnicianCommented:
Ok so place an alert inside your validation block, just before the Ajax call.

alert("reached");

Let me know if it run the alert
0
 
Lynn CurtDeveloperAuthor 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

0
 
leakim971PluritechnicianCommented:
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 %>")
0
 
Lynn CurtDeveloperAuthor Commented:
I believe I solved my problem (and it was a simple yet odd fix), though I'm really not sure WHY this worked.  Maybe you know.

Here's what I did.

First, I renamed my form id to "myForm".  I wanted it to be sort of generic.

I than wrapped the entire form in a div with its id set to "newIntake".   That "newIntake" was the original id that was assigned to the Form tag.

See here...

<h2>Intake Form</h2>

<div id="newIntake">
    <form id="myForm" name="myForm">
        <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>

        ....
</form>
</div>

Open in new window


As far as the jquery / ajax code; I didn't do a thing.  I left it as is.  Now, everything works?!?!?

I'm so very confused as to WHY it works this way.  Any ideas?
0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
leakim971PluritechnicianCommented:
glad you make it working, congrats
0
 
Lynn CurtDeveloperAuthor Commented:
Thanks for your help!
0
 
Lynn CurtDeveloperAuthor Commented:
I got it working!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.