2015-04-17 1 views
0

Я пытаюсь отобразить список категорий с частичным представлением. Класс «selected» следует применять к определенной категории, когда он выбран. Однако класс не применяется, если список возвращается как частичный вид.Класс CSS не применяется к вспомогательному расширению с частичным представлением

_layout страница:

<nav> 

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

</nav> 

Действие в главном контроллере:

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

расширения Helper

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> 
    

+0

ли ввести свой код или? В помощнике у вас есть & try put && – freshbm

+0

MenuLink является расширением класса html helper. && не имеет значения. – Rennos

+1

Вы пытались отлаживать, каково значение currentAction в случае partialView? – freshbm

ответ

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