我正在尝试以编程方式创建html.actionlink。到目前为止,我已经做了类似的事情
public static class MenuExtensions
{
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
var li = new TagBuilder("li");
RouteData routeData = htmlHelper.ViewContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentController = routeData.GetRequiredString("controller");
if (
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("active");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
}
在视图中
@Html.MenuItem("Insurance Providers", "Index", "Payer")
这将生成一个像这样的HTML
<li><a href="/Payer">Insurance Providers</a></li>
现在我想在该锚标记中包含一个bootstrapIcon,我想要的输出是这样的
<li><a href="/Payer">
<i class="linecons-desktop"></i>
<span class="title">Insurance Providers</span>
</a></li>
有人能告诉我如何实现这个目标吗?
答案 0 :(得分:1)
您需要在<a>
的帮助下手动构建Url.Action
标记,以生成正确的网址
public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller, string className )
{
StringBuilder html = new StringBuilder();
TagBuilder i = new TagBuilder("i");
i.AddCssClass("className");
StringBuilder html = new StringBuilder();
html.Append(i.ToString());
TagBuilder span = new TagBuilder("span");
span.InnerHtml = text;
span.AddCssClass("title");
html.Append(span.ToString());
UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
string href = urlHelper.Action(action, controller);
TagBuilder a = new TagBuilder("a");
a.MergeAttribute("href", href);
a.InnerHtml = html.ToString();
TagBuilder li = new TagBuilder("li");
li.InnerHtml = a.ToString();
return MvcHtmlString.Create(li.ToString());
}