Javascript redirecttoaction does not work

Asked

Viewed 523 times

0

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

If the insertion goes well I give RedirectToAction for the index of this same controller passing the id of the profile I just registered, but nothingness 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 forwarding it by javascript adding the return "Success".

Would this approach be correct? I’m starting out in web development and wanted some guidance on these "good practices". After all, the RedirectToAction my controller should work. Where I made the mistake?

Code with problem circumvented:

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);
        }
  • You are adding the [Httppost] annotation on top of the Add Action?

  • I believe that’s right, Httppost because window.location.href = "/User/List/" + id; it’s a GET, when you don’t add the [Httppost] annotation on top of your Action automatically by default it’s a [Httpget]. Try to add this on top of your [Httppost] Action and see if it has brought results.

  • Take a look at this question https://stackoverflow.com/questions/11767911/mvc-httppost-httpget-for-action

  • @Leonardo, actually 'window.location.href = User/List/" + id' functions! My problem is with the controller, where it does not redirect to the Index view of the Profile controller. httpPost in this case is explicit in the asynchronous $.ajax call with type: 'POST'.

  • But does it ever pass the Add Actionresult ? because this method in my view is a GET, if you instruct the server-side to run a Post it will look for the Post, I may be wrong... but it has happened to me, it comes to execute the action?

  • @Leonardobonetti he performs yes... I am debugging and he goes through the action Add yes. The problem is that when it falls on the line 'Return Redirecttoaction("Index", "Profile", profile.Id);' it absolutely nothing...

  • Ahhhh, now I understand.

  • @Lucasferriani And neither should you. This is the expected behavior.

Show 3 more comments

1 answer

0


Your first premise is quite wrong.

When making an asynchronous request for the server-side, you should return data or anything that is possible to handle on the client side using Javascript, doing a redirect will not cause any effect.

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

  • That was the answer I wanted to have. In case, is there any way that I can just call the controller without expecting any feedback and let him do the redirecting? The same way it works when I have a form in html with the action="/Controler/Action" attribute and I click on the Submit button?

  • No, young man. Because the JS won’t do anything a redirect code.

  • thank you man! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.