CSS class won't be applied to a helper extensi

2019-06-12 08:14发布

问题:

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