JDS JDS - 2 months ago 12
Javascript Question

"return false" not stopping postback to the controller

I have an MVC5 view and in this view I have:

@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
// My controls
<input type="submit" id="btnSubmit" class="btn btn-primary" value="Submit" />
}


What I want is to make an ajax call checking the record count prior to posting to the controller.

If the record count is high I want to stay on the view and prompt the user.

Everything appears to be working with the exception that the view is still posting to MyAction. I would have expected "return false;" to prevent that.

Why is "return false" not stopping the post to the controller?

$("#btnSubmit").click(function (e) {

var p1= $("#Value1").val();
var p2= $("#Value2").val();

$.ajax({
type: "GET",
url: "/MyController/GetRecordCount",
data: { "param1": p1, "param2": p2 },
async: false
}).done(function (recCount) {
if (recCount> 999)
{
$(".showAdditionalInfo").show();
return false;
}
}).fail(function (xhr, status, err) {
alert(xhr.responseText);
});
});

Answer

Your return should be within the click handler itself. Right now it is inside of the AJAX callback.

It should be this instead:

$("#btnSubmit").click(function (e) {
        e.preventDefault();
        var p1= $("#Value1").val();
        var p2= $("#Value2").val();
        var doPost = true;


        $.ajax({
            type: "GET",
            url: "/MyController/GetRecordCount",
            data: { "param1": p1, "param2": p2 },
            async: false
        }).done(function (recCount) {
            if (recCount> 999)
            {
                $(".showAdditionalInfo").show();
                doPost = false;
            }
        }).fail(function (xhr, status, err) {
            alert(xhr.responseText);
        });

        return doPost;
    });

This assumes that the ajax request will not be async. Once it is then this shouldn't work anymore.

Comments