In fact, in addition to jQuery you need the jQuery Unobtrusive Ajax Microsof plugin 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 function OnSuccess :
<script type="text/javascript">
function OnSuccess(response) {
if (response && response.data) // verifica se response e se response.data existe
alert(response.data);
}
</script>
This way you can use Ajax.BeginForm
. If you want to avoid another plugin just for sending Ajax requests , you can do this 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);
});
}
});
});