CSS类不会应用于具有局部视图的辅助扩展 [英] CSS class won't be applied to a helper extension with a partial view
本文介绍了CSS类不会应用于具有局部视图的辅助扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过部分视图显示类别列表.选择类别"时,应将其应用于特定类别.但是,如果列表作为部分视图返回,则不会应用该类.
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.
_布局页面:
<nav>
@Html.Action("_getCategories", "Home")
</nav>
Home控制器中的操作:
Action in Home controller:
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>
推荐答案
您正在调用子操作,因此您需要先获取其父ViewContext
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);
}
这篇关于CSS类不会应用于具有局部视图的辅助扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文