简体   繁体   中英

Form not validating on client side after implementing ajax

The Index page has a partial view (ReservSearch.cshtml) to enter the search arguments and another to display the result (Rates.cshtml) via ajax, that calls the GetRates() action in the HomeController.

Before using the ajax call, the form was validating correctly, ie, it didn't call the GetRates() action unless all the required fields were filled in, but the Rates partial view was displaying in another page of its own, thus the ajax call to display it correctly in the Index page.

After implementing the ajax call, the Rates View displays where it is supposed to be, in a div on the Index page, assuming the user entered all values correctly before clicking the submit button.

The problem is that, now, whenever the form is submitted, it always call the GetRates() Action method in the controller, even if there is no values entered in the form. It still works, because the ajax executes the error function and not the success, but I wonder if this is the proper way to do it and if my code is correct.

// VIEW: ReservSearch.cshtml

@model Models.ReservSearch

@using (Html.BeginForm("GetRates", "Home", FormMethod.Post, new { @id = "reservSearch"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        @Html.TextBoxFor(model => model.DropOffDate)
        @Html.ValidationMessageFor(model => model.DropOffDate)
    </div>

    <div>
        @Html.TextBoxFor(model => model.PickUpDate)
        @Html.ValidationMessageFor(model => model.PickUpDate)
    </div>


    <div>
        <input type="submit" value="GET RATES"/>
    </div>

}

<script>
    $(function () {
        $('#reservSearch').submit(function () {

            $.ajax({
                url: '/Home/GetRates',
                type: "POST",
                dataType: 'html',
                data: $("#reservSearch").serialize(),
                success: function (data) { $('#ratesView').html(data); }, //Fill div with results
                //error: function () { alert('Error: #reservSearch()'); }
            });
            // it is important to return false in order to cancel the default submission of the form and perform the AJAX call (copied from another post)
            return false;

        });
    });
</script>


enter code here

// HOME CONTROLLER

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetRates([Bind(Include = "DropOffLoc,DropOffDate,PickUpDate")] ReservSearch reservSearch)
{
    if (ModelState.IsValid)
    {
        // Code ....
        return PartialView("~/Views/Shared/Rates.cshtml", rates);
     }
     return PartialView("~/Views/Shared/ErrorInfo.cshtml");
}

You should check whether your form is valid and after that make an ajax call:

$('#reservSearch').submit(function () {
    if($(this).valid()) {
         // ajax call
    }
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM