Question:
I have my Form
with the following declaration:
@using (Ajax.BeginForm("Novo","Cliente", new AjaxOptions
{
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
}))
{ }
My functions in js:
function OnSuccess(response) {
alert(response);
}
function OnFailure(response) {
alert(response);
}
And my Controller :
public ActionResult Novo(MyModel model)
{
if (ModelState.IsValid)
{
return Json(new { data = 1 }, JsonRequestBehavior.AllowGet);
}
return View(model);
}
But it doesn't call my functions, it returns a Json on the whole page. What is wrong?
Answer:
In fact besides jQuery you need the Microsof jQuery Unobtrusive Ajax plugin which you can get via NuGet .
So the minimum structure to carry out the process is:
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
And the helper is at least like this:
@using (Ajax.BeginForm("Novo", "Cliente", new AjaxOptions
{
OnSuccess = "OnSuccess"
}))
{
<button type="submit">Submit</button>
}
And the JavaScript OnSuccess function:
<script type="text/javascript">
function OnSuccess(response) {
if (response && response.data) // verifica se response e se response.data existe
alert(response.data);
}
</script>
That way you can use Ajax.BeginForm
. If you want to avoid another plugin just for sending Ajax requests, you can do it manually without the need for Unobtrusive Ajax:
@using(Html.BeginForm("Novo", "Cliente", FormMethod.Post, new { id = "formCliente" }))
{
<button type="submit">Submit</button>
}
With a script:
$(function () {
$("#formCliente input[type=submit]").click(function (event) {
event.preventDefault();
var form = document.getElementById("formCliente");
var data = $(form).serialize();
$.post(form.action, data, function (response) {
if (response && response.data)
alert(response.data);
});
});
});
And if you use Unobtrusive Validate :
$(function () {
$("#formCliente input[type=submit]").click(function (event) {
event.preventDefault();
var $form = $("#formCliente");
$form.validate();
if ($form.valid) {
var data = $form.serialize();
$.post($form.attr("action"), data, function (response) {
if (response && response.data)
alert(response.data);
});
}
});
});