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

左心房为你撑大大i 提交于 2019-12-08 09:16:24

问题


I am trying to display a list of categories with a partial view. The class "selected" should be applied to a specific category when it is selected. However, the class does not get applied if the list is return as a partial view.

_Layout page:

<nav>

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

</nav>

Action in Home controller:

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

Helper extension

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);
    }

Partial view:

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


    回答1:


    Your calling a child action, so your need to get its parent ViewContext first

    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);
    }
    


    来源:https://stackoverflow.com/questions/29692877/css-class-wont-be-applied-to-a-helper-extension-with-a-partial-view

    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!