我有一个Helper类,它将当前控制器设置为活动的navbar项。它还考虑了下拉导航。
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller,
Dictionary<string, string> dropdown
)
{
var li = new TagBuilder("li");
var dropdownList = new TagBuilder("ul");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("active");
}
li.AddCssClass("menuitem");
if(dropdown != null)
{
li.AddCssClass("dropdown");
foreach (var item in dropdown)
{
var dropdownli = new TagBuilder("li");
dropdownli.InnerHtml = htmlHelper.ActionLink(item.Key, item.Key, item.Value, null, null).ToHtmlString();
dropdownList.InnerHtml += dropdownli;
}
dropdownList.AddCssClass("dropdown-menu");
li.InnerHtml = htmlHelper.ActionLink(text, action, controller, null, new { @class="dropdown-toggle", data_toggle="dropdown"}).ToHtmlString() + dropdownList.ToString();
}
else
{
li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
}
return MvcHtmlString.Create(li.ToString());
}
Helper类在_Layout.cshtml中调用,如下所示:
@Html.MenuItem("Home", "Index", "Home", null)
@Html.MenuItem("News", "Index", "News", null)
@Html.MenuItem("Media", "Index", "Media",
new Dictionary<string, string>() {{ "Photos", "Media" },
{ "Videos", "Media" }})
@Html.MenuItem("Events", "Index", "Events",
new Dictionary<string, string>() {{ "FirstEvent", "Events" },
{ "SecondEvent", "Events" }})
@Html.MenuItem("Donate", "Index", "Donate",
new Dictionary<string, string>() {{ "Sponsor", "Donate" }})
问题在于,对于每个导航栏项,每个链接的名称是操作的名称,这意味着如果操作是“FirstEvent”,则它将显示为“FirstEvent”而不是“First Event”。 / p>
无论如何我可以做[ActionName(“First Event”)]之类的东西来设置名称,然后在Helper类中调用它?
[ActionName("Culture Show")]
public ActionResult CultureShow()
{
return View();
}
答案 0 :(得分:1)
您可以使用反射来扫描动作方法的ActionName
属性,但似乎更容易的解决方案是使用模型而不是字典。
public class HyperlinkDataModel
{
public string LinkText { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
}
@Html.MenuItem("Events", "Index", "Events",
new[] {
new HyperlinkDataModel {
ActionName = "FirstEvent", ControllerName = "Events", LinkText = "First Event"
},
new HyperlinkDataModel {
ActionName = "SecondEvent", ControllerName = "Events", LinkText = "Second Event"
}
})
然后在HtmlHelper中执行此操作:
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller,
IList<HyperlinkDataModel> dropdown
)
{
...
foreach (var item in dropdown)
{
var dropdownli = new TagBuilder("li");
dropdownli.InnerHtml = htmlHelper.ActionLink(item.LinkText, item.ActionName,
item.ControllerName, null, null).ToHtmlString();
dropdownList.InnerHtml += dropdownli;
}