RedirectToAction in JavaScript does not work

0

After a validation I call the controller in the action (Add) to add a new record through javascript.

If the insertion succeeds I give RedirectToAction to the index of this same controller passing the id of the profile that I just registered, however nothing happens!

JavaScript:

function validaFormulario() {
    var formularioValidado = false;

    formularioValidado = validaFormulario();

    if (formularioValidado) {
        var perfil = obtemPerfilDoFormulario();
        $.ajax({
            type: 'POST',
            url: '/Perfil/Adiciona',
            data: {
                "perfil": perfil
            },
            async: false,
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    }
}

Controller:

public ActionResult Adiciona(Perfil perfil)
{
    PerfilDAO perfilDAO = new PerfilDAO();
    perfil.UsuarioId = usuario.Id;
    perfilDAO.Adiciona(perfil);

    EnviaEmailRecebimentoCadastro(perfil.Email);

    EnviaEmailAtivacaoDeConta(perfil.Email);

    return RedirectToAction("Index", "Perfil", perfil.Id);
}

I was able to get around the problem by sending the profile id by Json and manually doing the redirect by adding the javascript "success" return.

Would this approach be correct? I am starting in web development and wanted guidance on these "good practices". After all,% w / w of my controller should work. Where did I make the mistake?

Code with problem bypassed:

Controller sending Json:

public ActionResult Adiciona(Perfil perfil)
{
    //restante do codigo

    return Json(perfil.Id);
}

Javascript with success:

    $.ajax({
        type: 'POST',
        url: '/Perfil/Adiciona',
        data: {
            "perfil": perfil
        },
        async: false,
        success: function (data) {
            var id = JSON.parse(data);
                window.location.href = "/Usuario/Lista/" + id;
        },
        error: function (xhr, status, error) {
            alert(error);
        }
    
asked by anonymous 31.07.2017 / 15:32

1 answer

0

Your first premise is quite wrong.

When making an asynchronous request to the server-side , you should return data or anything that could be handled by the client side using JavaScript, doing a redirect will have no effect at all. >

The second idea is the best way to do what you want. In it the Ajax request is made to the server, it returns the data so that the client (JavaScript) is in charge of the redirect.

    
31.07.2017 / 15:44