因此,我遇到了 MVC ActionLink 和引导下拉菜单的问题。我成功地使用了简单的菜单扩展,在其中传递了字符串和一个布尔值之类的参数。But now I am trying to make my own extension which could generate Bootstrap Dropdown and add selected css class to parent of the dropdown - "ONEofTHEdropdownITEMSselected" - when one of those items in dropdown is selected (when selecting dropdown item it routes to different controller there fore 可以是几个或多个控制器):
<a href="#" class="dropdown-toggle ONEofTHEdropdownITEMSselected" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
和
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="~/area/controller1">Action1</a></li>
<li><a href="~/area/controller2">Action2</a></li>
</ul>
</li>
下面是我想要实现的 UI/MenuExtensions.cs - 传递两个可以生成引导下拉列表的参数,我可以在该下拉列表中手动插入新的菜单项。
public static class MenuExtensions
{
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller,
string cssClass = "item",
bool isController = false
)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if ((string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) || isController) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
li.AddCssClass("am-selected");
li.InnerHtml = htmlHelper.ActionLink(text, action, controller, new { Area = "" }, new { @class = cssClass }).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
public static MvcHtmlString SelectMenu(
this HtmlHelper htmlHelper,
string cssClass,
SelectMenuItem[] menuItems
)
{
TagBuilder list = new TagBuilder("li")
{
InnerHtml = ""
};
string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
foreach (SelectMenuItem menuItem in menuItems)
{
TagBuilder li = new TagBuilder("li")
{
InnerHtml = htmlHelper.ActionLink(menuItem.Text, menuItem.Action, menuItem.Controller, null, new { }).ToHtmlString()
};
ul.InnerHtml += li.ToString();
}
return MvcHtmlString.Create(list.ToString());
}
}
这是外部类
public class SelectMenuItem
{
public string Text { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
public bool IsVisible { get; set; }
public SelectMenuItem()
{
IsVisible = true;
}
}
之后我的 html 看起来像这样。
@Html.SelectMenu("dropdown", new []{
new SelectMenuItem{ Text = "ViewOne", Controller = "Controller1", Action = "index", IsVisible = SystemUser.Current().IsAdmin},
new SelectMenuItem{ Text = "ViewTwo", Controller = "Controller2", Action = "index"}
});
问题是 SelectMenu 只呈现这个:
<li></li>