None
None

Reputation: 5670

Add bootstrap Icon to menu by extension method

I am trying to create an html.actionlink programatically. So far I have made something like this

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());
    }
}

And in View

  @Html.MenuItem("Insurance Providers", "Index", "Payer")

This will generate an HTML like this

<li><a href="/Payer">Insurance Providers</a></li>

Now I want to include a bootstrapIcon inside that anchor tag, My desired out put is like this

<li><a href="/Payer">
 <i class="linecons-desktop"></i>
   <span class="title">Insurance Providers</span>
     </a></li>

Can anyone tell me how I could achieve this?

Upvotes: 0

Views: 288

Answers (1)

user3559349
user3559349

Reputation:

You will need to construct the <a> tag manually with the help of Url.Action to generate the correct url

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());
}

Upvotes: 1

Related Questions