Returning with Ajax BeginForm

6

I have my Form with the following statement:

@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 does not call my functions, it returns a Json on the whole page. What's wrong?

    
asked by Rod 03.10.2014 в 19:14

1 answer

9

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);
            });
        }
    });
});
    
03.10.2014 / 20:04