Link to home
Start Free TrialLog in
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

Avatar of leakim971
leakim971
Flag of Guadeloupe image

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

Open in new window

Avatar of Sarah Ward

ASKER

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

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

alert("reached");

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

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
Avatar of Sarah Ward
Sarah Ward
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your help!
I got it working!