0

I have a custom html helper:

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

Sometimes I would like to add some html attributes to this anchor. For example, I would like to add an additional class to this link. I try this:

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

But it doesn't work because the class already exist (dialoglink).

How can I proceed to be able to add more css to my link with htmlAttributes?

Thanks

2 Answers 2

4

You should add the dialogLink class after merging the attributes to avoid overriding it:

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());
}
Sign up to request clarification or add additional context in comments.

Comments

0

Also you can use

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

link to msdn

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.