Nathanael Nathanael - 3 months ago 11
Ajax Question

How can I stop the JSON I get (from an MVC Controller) from being displayed on a new page?

I'm hip-deep in an ASP.NET MVC project and have realized that there's something I ought to be doing with AJAX. I'm new at AJAX so I've started with a little test function, but can't even get that to work. Seems like I'm very close though.

On the View I have:

@using (Html.BeginForm("Add4", "Configurators", FormMethod.Post))
{
<input type="number" name="addend" id="addend" />
<input type="submit" name="add4go" id="add4go" value="Add 4 to it" />
}
<script>
$(document).ready(function () {
$("#add4go").click(function () {
$.ajax({
type: 'POST',
url: '/Configurators/Add4',
dataType: 'json',
data: { addend: $("#addend").val() },
success: function (data) {
alert(data[sum]);
}
});
});
});
</script>


In ConfiguratorsControllers I have this function:

[HttpPost]
public ActionResult Add4( int addend )
{
int theSum = addend + 4;
return (Json(new { sum = theSum }));
}


What I want: I type in, say, 5, then click on "Go", and the 5 is replaced with a 9.

What I get: I type in 5, then click on "Go", and the browser takes me to an entirely new page at /configurators/add4, which contains only:

{"sum":9}


What am I doing wrong?

Answer

your form posts back to the same URL your ajax function calls and is posting back after you call your ajax code so it's just going to behave like you didn't put any ajax handler there at all.

return 'false' in the click handler so it does not post back or change to type=button or use a standard hyperlink.

@using (Html.BeginForm("Add4", "Configurators", FormMethod.Post))
{
    <input type="number" name="addend" id="addend" />
    <input type="submit" name="add4go" id="add4go" value="Add 4 to it" />
}
<script>
    $(document).ready(function () {
        $("#add4go").click(function () {
            $.ajax({
                type: 'POST',
                url: '/Configurators/Add4',
                dataType: 'json',
                data: { addend: $("#addend").val() },
                success: function (data) {
                    alert(data[sum]);
                }
            });
          return false;
        });
    });
</script>