来自 Html.DropDownList 的 MVC 调用操作方法

MVC call action method from Html.DropDownList

_布局:

@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>
                        }

当用户单击注销选项下拉列表时,我需要像使用 ActionLinks 一样调用 Logout() 方法。我该怎么做?

编辑: 注销不适用于新的 jquery 代码。这是为什么?

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

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

虽然我的旧代码通过注销用户仍然有效。

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

你可以这样做,假设你使用的是 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>

或者,您可以使用这些项目创建无序列表,这些项目将在单击或悬停其他元素时显示。当然,您必须设计它的样式。这样你就可以使用 ActionLink。 MVC.Authentication.LogOut() 只是注销操作的示例。

<div class="myDropdown">
    <ul>
        <li>User.Identity.Name</li>
        <li>@Html.ActionLink("Log out", MVC.Authentication.LogOut())</li>
    </ul>
</div>