0

_Layout:

@if (User.Identity.IsAuthenticated)
                        {
                            <li>@Html.DropDownList("User", new List<SelectListItem>
                           {
                               new SelectListItem { Text = User.Identity.Name, Value = "1", Selected = true },
                               new SelectListItem { Text = "Logout", Value = "2" }
                           })</li>
                        }

When the user clicks on the logout option drop down list I need to call the Logout() method like you can with ActionLinks. How do I do this?

Edit: Signout isn't working with new jquery code. Why is this?

public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

        return View("../Home/Index");
    } 

My old code still works though by logging user off though.

  <li>@Html.ActionLink("Logout", "Logout", "Users", new { }, new { @class = "nav-link" })</li>

1 Answer 1

1

You could do something like this, assuming you are using jQuery:

<script type="text/javascript">
    $(function() {
        $('#User').on('change', function (event) {
            if (event.currentTarget.selectedIndex === 1) {
                // redirect to your logout controller, redirect
                window.location.href = '/controller/logoutaction';
            }
        });
    });
</script>

Alternatively you could do unordered list with these items, that would be displayed on click or hover of some other element. Of course you'd have to style it. This way you could use ActionLink. MVC.Authentication.LogOut() is just example Action to logout.

<div class="myDropdown">
    <ul>
        <li>User.Identity.Name</li>
        <li>@Html.ActionLink("Log out", MVC.Authentication.LogOut())</li>
    </ul>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Probably because that did an AJAX request just to log you out. I've updated an example with a simple redirect to your controller, maybe that's what you want. Check the console on browser for any errors.I'd also suggest you that after logout you don't just return the view View("../Home/Index"); but return redirect to action. Something like return RedirectToAction(MVC.Logout.Logout());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.