Quiver Quiver - 1 month ago 13
Ajax Question

Ajax call not hitting controller action

I am trying to send a

FormCollection
to an action in my controller but the action is never being hit.

Form:

<form class="form-horizontal" role="form" id="TestForm" onsubmit="return false">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" name="Blah1" />
<input type="text" name="Blah2" />
</div>
<input id="SubmitButton" type="submit" value="Submit" />
</div>
</div>




jQuery/Ajax:

$(document).ready(function () {
$("#SubmitButton").click(function () {
var form = $("#TestForm").serialize();


$.ajax({
url: "/Calculator/Post",
type: "POST",
data: form,
dataType: 'json',
success: function () {
alert("Success");
},
error: function () {
alert("Error");
}
});
});
});


Controller Action:

[HttpPost]
public JsonResult Post(FormCollection form)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}


The only thing that happens is the browser alerts the error message. Am I missing something that is causing the action to never be hit?

Answer

Your code should work fine as posted in the question. The only issue is see is how you are building the url manually which might cause 404 issues sometimes depending on your current url/page. You should be using the Url.Action helper method to build the urls which will take care of building the correct relative url regardless of which page you are currently in.

serialize() method is good enough to send your form data. It should work fine(go ahead and try it). you do not need to call the serializeArray and then stringify it as suggested by the accepted answer !

$.ajax({
    url: "@Url.Action("Post","Calculator")",
    type: "POST",
    data: $("#TestForm").serialize(),
    dataType: 'json',
    success: function () {
        alert("Success");
    },
    error: function () {
        alert("Error");
    }
});

If you are making this ajax call in an external js file, you may consider passing the base url to the js file and use that to build the relative url to your action method as described in this answer.

Also, in your action method, you do not need to pass the JsonRequestBehavior.AllowGet parameter to the Json method as your Action method is marked with [HttpPost]

[HttpPost]
public JsonResult Post(FormCollection form)
{
    var item =form["Blah1"];
    return Json(new { success = true });
}