我正在尝试将点击的标签设为“已选中”。如果我可以以编程方式获取值集,我有一个class ='selected'可以正确设置它。我正在使用一种主要工作的扩展方法,它在链接上设置class ='selected'而不是li。如果我能以某种方式设置li class ='selected'那么它将起作用。有什么想法吗?
由于
<div id="tabs" class="shadetabs">
<ul>
<li id="tab10" class="test">@Html.MenuLink("Overview", "Index", "Statistics")</li>
<li id="tab20" class="test">@Html.MenuLink("Detail View", "Detail", "Statistics")</li>
<li id="tab30" class="test">@Html.MenuLink("Trends", "Trends", "Statistics")</li>
</ul>
</div>
public static class HTMLHelper
{
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
{
var routeData = htmlHelper.ViewContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentController = routeData.GetRequiredString("controller");
if (actionName == currentAction && controllerName == currentController)
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" });
}
return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
}
答案 0 :(得分:0)
这是你可以做到的一种方式..
<ul id="menu">
<li id="tab10" class="test @Html.AddClassIfRouteMatches("Home", "Index", "Home", "selected")">@Html.ActionLink("Home", "Index", "Home")</li>
<li id="tab20" class="test @Html.AddClassIfRouteMatches("Detail View", "Detail", "Statistics", "selected")">@Html.ActionLink("Detail View", "Detail", "Statistics")</li>
<li id="tab30" class="test @Html.AddClassIfRouteMatches("Detail View", "Detail", "Statistics", "selected")">@Html.ActionLink("Trends", "Trends", "Statistics")</li>
</ul>
public static string AddClassIfRouteMatches(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string selectedClassName)
{
var routeData = htmlHelper.ViewContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentController = routeData.GetRequiredString("controller");
if (actionName == currentAction && controllerName == currentController)
{
return selectedClassName;
}
return string.Empty;
}
如果当前路由与我们的参数匹配,我们可以使用帮助器来渲染字符串,而不是渲染任何东西。这样,您就不会失去所有ActionLink覆盖的可用性。