Net Core: TagBuilder Edit an Existing Attribute

459 Views Asked by At

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");
1

There are 1 best solutions below

1
pfx On BEST ANSWER

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>