CSS class 不会应用于具有局部视图的辅助扩展

CSS class won't be applied to a helper extension with a partial view

我正在尝试以局部视图显示类别列表。 class "selected" 应在选择时应用于特定类别。但是,如果列表是 return 作为部分视图,则不会应用 class。

_布局页面:

<nav>

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

</nav>

家庭控制器中的操作:

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

您调用的是子动作,因此您需要先获取其父动作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);
}