2011-12-15 55 views
4

可能重複:
How to put span element inside ActionLink MVC3?如何創建自定義的MVC3 ActionLink方法?

如何創建生成的輸出定製MVC3 ActionLink的方法:

<li> 
    <a href="/Home/ControllerName" data-ajax-update="#scroll" 
    data-ajax-mode="replace" data-ajax-method="GET" 
    data-ajax-loading="#progress" data-ajax="true"> 

    <span>LinkText</span> // this span generated inside <a> 

    </a> 
</li> 
+0

請不要重複你只在這裏問過的同一個問題http://stackoverflow.com/questions/8518109/how-to-put-span-element-inside-actionlink-mvc3 – Maheep 2011-12-15 10:40:50

回答

7

你既可以創建一個返回MvcHtmlString一個新的擴展方法對象,你自己放在一起(雖然介意html編碼),我們創建了一個可以在需要時渲染的局部視圖,因此您不必通過代碼創建HTML。

public static class MyHtmlExtensions { 
    public static MvcHtmlString MyActionLink(this HtmlHelper html, string action, string controller, string ajaxUpdateId, string spanText) { 
     var url = UrlHelper.GenerateContentUrl("~/" + controller + "/" + action); 
     var result = new StringBuilder(); 
     result.Append("<a href=\""); 
     result.Append(HttpUtility.HtmlAttributeEncode(url)); 
     result.Append("\" data-ajax-update=\""); 
     result.Append(HttpUtility.HtmlAttributeEncode("#" + ajaxUpdateId)); 
     // ... and so on 

     return new MvcHtmlString(result.ToString()); 
    } 
} 
2

您將不得不爲剃鬚刀創建自定義HTML助手。這樣,您可以爲鏈接呈現自定義HTML(包括您對span標記的要求)。這個助手擴展方法必須返回一個MvcHtmlString對象。

creating HTML helper的一個例子可以在這裏找到。