How to do Logoff with Ajax?

Asked

Viewed 115 times

0

I have my menu, and it has a dropdown

<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Usuário</a>
    <ul class="dropdown-menu" role="menu">
        <li><a href="/">Meus dados</a></li>
        <li><a href="#" id="LogOff">Sair</a></li>
    </ul>
</li>

I tried to use the "Get out"

using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm"}))
{
@Html.AntiForgeryToken()

<ul class="nav navbar-nav">

    <li><a href="javascript:document.getElementById('logoutForm').submit()">Sair</a></li>
</ul>
}

But it breaks with the menu by rendering a Form

I tried then with Ajax

$("#LogOff").on("click", function (e) {
    $.post('@Url.Content("~/Account/LogOff")');
});

So he sends the Post, but I have to give "Refresh" go to the login, ignoring the RedirectToAction that is in the action LogOff and also does not accept the ValidateAntiForgeryToken

1 answer

2


Redirect will not work for ajax requests. You have to split into two parts.

Ex:

<script>
    $(function(){
        $("#logoutForm").click(function(e){
            e.preventDefault();

            $.post('@Url.Content("~/Account/LogOff")', null, function(){
                window.location = '/Account/Login';
            });

        });

    });
</script>

Browser other questions tagged

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