2012-03-01 53 views
0

插入附加類,我的鏈接使用htmlAttributes我有一個自定義的HTML幫助:對我的幫助

public static MvcHtmlString MyLink(this HtmlHelper htmlHelper, string linkText, object htmlAttributes) 
{ 
    TagBuilder builder = new TagBuilder("a"); 
    builder.SetInnerText(linkText); 
    builder.AddCssClass("dialogLink"); 
    return new MvcHtmlString(builder.ToString()); 
} 

有時候我想補充一些HTML屬性這種定位的。例如,我想一個額外的類添加到這個鏈接。我試試這個:

public static MvcHtmlString MyLink(this HtmlHelper htmlHelper, string linkText, object htmlAttributes) 
{ 
    TagBuilder builder = new TagBuilder("a"); 
    builder.SetInnerText(linkText); 
    builder.AddCssClass("dialogLink"); 

    if (htmlAttributes != null) 
     builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 

    return new MvcHtmlString(builder.ToString()); 
} 

但它不工作,因爲類已經存在(dialoglink)。

我怎麼能繼續能夠更多的CSS添加到我的htmlAttributes鏈接?

感謝

回答

4

你應該合併屬性之後添加dialogLink類,以避免覆蓋它:

public static IHtmlString MyLink(this HtmlHelper htmlHelper, string linkText, object htmlAttributes) 
{ 
    var builder = new TagBuilder("a"); 
    builder.SetInnerText(linkText); 
    if (htmlAttributes != null) 
    { 
     builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); 
    } 
    builder.AddCssClass("dialogLink"); 
    return new HtmlString(builder.ToString()); 
} 
0

您也可以使用

if (htmlAttributes != null) 
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); 

link to msdn

public void MergeAttribute(
    string key, 
    string value, 
    bool replaceExisting 
)