重定向视图未显示“活动”;属性

Redirected View not displaying "active" attribute in MVC application

本文关键字:属性 活动 视图 显示 重定向      更新时间:2023-09-26

我有一个新的MVC 4应用程序,我正在玩。基本上,顶部有几个菜单项,当前活动的页面用以下JavaScript在我的_Layout.cshtml中突出显示:

<script type="text/javascript">
    $(document).ready(function () {
        $('#top-navbar .nav a[href="' + this.location.pathname + '"]').parent().addClass('active');
    });
</script>

这在通过顶部的菜单导航时非常有效。然而,我添加了一个"登录"功能,如果用户在登录后试图返回登录页面,它将简单地向他们发送Index视图而不是Login视图。问题是,CSS仍然在菜单中突出显示Login按钮,而不是Home按钮。

我通过Session状态持久化用户的登录信息。这里是Login() ActionResult:

[HttpGet]
public ActionResult Login()
{
    if (Session["ContactName"] != null)
    {
        return View("Index");
    }
    else
    {
        return View();
    }
}

正如你所看到的,如果ContactName不是null,那么他们已经登录了,所以它向他们发送Home视图。我应该把Redirect()改为主页吗?

如果需要,这里是菜单navbar:

<ul class="nav navbar-nav">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About Us", "About", "Home")</li>
    <li>@Html.ActionLink("Customer Login", "Login", "Home")</li>
</ul>

问题是您的客户端仍然将URL视为/Login而不是索引,因此您最好重定向用户。您可以使用RedirectToAction controller方法并为它指定返回索引视图的控制器和操作名称:

[HttpGet]
public ActionResult Login()
{
    if (Session["ContactName"] != null)
    {
        return RedirectToAction("Index", "Home");
    }
    else
    {
        return View();
    }
}

你可以删除设置活动菜单的JQuery,并在你的导航栏标签中使用它:

<ul class="nav navbar-nav">
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

或者你可以实现一些HtmlHelper来做同样的事情,就像这篇文章中显示的那样:http://chrisondotnet.com/2012/08/setting-active-link-twitter-bootstrap-navbar-aspnet-mvc/