Search code examples
c#asp.net-coreasp.net-core-mvc.net-core-2.0tag-helpers

Net Core: TagBuilder Edit an Existing Attribute


I want to edit/modify the CSS class for an existing TagBuilder.

Currently the Tag is:

div.Attributes.Add("class", "checkbox");

I want to change it to below, after the previous statement already executed.

div.Attributes.Add("class", "book");

How would I conduct this? Currently I have to Delete/Remove Attribute, and Readd. Just curious if there is more efficient way.

checkbox.Attributes.Remove("class");
checkbox.MergeAttribute("class", "book");

Solution

  • Use the MergeAttribute overload accepting a boolean to overwrite the existing value.

    From the documentation

    Adds a new attribute or optionally replaces an existing attribute in the opening tag.

    TagBuilder div = new TagBuilder("div");
    
    div.Attributes.Add("class", "checkbox");
    // <div class="checkbox"></div>
    
    div.MergeAttribute("class", "book", true);
    // <div class="book"></div>