我已经看到这有几种不同的方式,但不是我正在寻找的具体方式。我目前有一个自定义 HtmlHelper,它将“class='currentPage'”添加到 ActionLink 以突出显示导航系统中的当前页面。
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
string value;
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))
{
value = htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();
return MvcHtmlString.Create(value.ToString());
}
value = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
return MvcHtmlString.Create(value.ToString());
}
这很好用,但我有一个管理区域,其中还有一个与每个菜单项关联的图像。该图像位于链接中,如下所示:
<li><a href="/Admin/Blog"><img src="/Content/images/icons/page_edit.png" alt="" /> Blog</a></li>
我想为“MenuItem”创建一个覆盖方法,在 ActionLink 中添加图像,但我有点难过。目前我有以下内容,将 img 标签放在外面......
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
bool isAdmin,
string text,
string action,
string controller
)
{
string value;
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
value = "<img src='/Content/images/admin_icons/" + text + ".png' alt='' /> ";
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
value += htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();
}
else
{
value += htmlHelper.ActionLink(text, action, controller).ToHtmlString();
}
return MvcHtmlString.Create(value.ToString());
}
有任何想法吗?