2015-02-12 85 views
0

我想通過編程方式創建一個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") 

這會產生這樣的

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

的HTML現在我想包括錨標記內bootstrapIcon ,我的理想輸出是這樣的

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

任何人都可以告訴我如何實現這一目標?

+0

將它總是產生''或者你會需要傳遞''標籤的類名稱? – 2015-02-12 06:13:40

+0

@StephenMuecke我想通過類名:) – Athul 2015-02-12 06:30:28

回答

1

您將需要與Url.Action幫助手動構造<a>標籤生成正確的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()); 
} 
相關問題