【问题标题】:Redirected View not displaying "active" attribute in MVC application重定向视图未在 MVC 应用程序中显示“活动”属性
【发布时间】:2015-05-20 22:10:23
【问题描述】:

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

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

【问题讨论】:

  • 您应该返回RedirectToAction("Index", "Home")。您所拥有的只是使用索引视图,但 url 仍将反映登录状态。

标签: javascript c# asp.net-mvc-4 razor


【解决方案1】:

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

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

【讨论】:

  • 啊,RedirectToAction() 正是我想要的!
【解决方案2】:

您可以删除您的 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/

【讨论】:

  • 这很好用。我试图找到一个不错的解决方案,而 JQuery 是我之前能想到的最简单的解决方案。这个很好,不需要任何脚本!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
相关资源
最近更新 更多