【问题标题】:CSS class won't be applied to a helper extension with a partial viewCSS 类不会应用于带有局部视图的辅助扩展
【发布时间】:2015-04-17 16:08:23
【问题描述】:

我正在尝试显示带有部分视图的类别列表。 “选定”类应在选定时应用于特定类别。但是,如果列表作为部分视图返回,则不会应用该类。

_布局页面:

<nav>

    @Html.Action("_getCategories", "Home")

</nav>

Home 控制器中的操作:

public ActionResult _getCategories()
    {
        var Categories = repository.getCategories();
        return PartialView(Categories);
    }

辅助扩展

public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string actionName, string controllerName)
    {
        string currentAction = helper.ViewContext.RouteData.GetRequiredString("action");
        string currentController = helper.ViewContext.RouteData.GetRequiredString("controller");
        if (actionName.Equals(currentAction) & controllerName.Equals(currentController))
        {
            return helper.ActionLink(text, actionName, controllerName, null, new { @class = "selected" });
        }
        return helper.ActionLink(text, actionName, controllerName);
    }

局部视图:

@using Project1.Context

    @foreach (var c in Model)
    {
        //Display categories in Model
    }
    <li>@Html.MenuLink("Home", "Index", "Home")</li>
    <li>@Html.MenuLink("About", "About", "Home")</li>
    <li>@Html.MenuLink("Contact", "Contact", "Home")</li>
    

    【问题讨论】:

    • 是输入你的代码还是?在助手中你有 & 尝试把 &&
    • MenuLink 是 html 助手类的扩展。 && 没有区别。
    • 你有没有调试过,在partialView的情况下currentAction的值是多少?

    标签: css asp.net-mvc partial-views


    【解决方案1】:

    您调用子操作,因此您需要先获取其父 ViewContext

    public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string actionName, string controllerName)
    {
        ViewContext parentContext = helper.ViewContext.ParentActionViewContext;
        string currentAction = parentContext.RouteData.GetRequiredString("action");
        string currentController = parentContext.RouteData.GetRequiredString("controller");
        if (actionName.Equals(currentAction) && controllerName.Equals(currentController))
        {
            return helper.ActionLink(text, actionName, controllerName, null, new { @class = "selected" });
        }
        return helper.ActionLink(text, actionName, controllerName);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 2011-08-22
      • 2023-04-11
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多