c# personal attribute to an html tag

A Visitor to my site came from google looking for "c# personal attribute to an html tag". If I understand this query correctly then the person is trying to add an attribute to an already created HTML object. However, this might not be the case, so I will include in this entry a few different ways of adding attibutes to HTML elements via C#.

Firstly, I am presuming that they are using IE to view the HTML. IE is pretty cool about attributes being added to HTML elements. They treat these attributes on HTML like expando objects (you can add them dynamically in JavaScript too). So an element <b id="testB"> can have an attribute kinlaniscool simply by using the following JavaScript: document.all.testB.kinlaniscool="false"; It could have been defined in the HTML as <b id="testB" kinlaniscool="false"> and you would get the same results.

To do this from C#, if you are rendering out a serverside control you could simply have the following:

HtmlGenericControl b = new HtmlGenericControl("b");b.ID="test";......b.Attributes.Add("kinlaniscool", false);this.Page.Controls.Add(b);

The above code might add a control to the page which is a "b" tag and that will look like: <b id="testB" kinlaniscool="false">

If you wanted to do something similar in a custom server control, I might do the following:

protected override void Render(HtmlTextWriter output){output.AddAttribute("kinlaniscool", "false");output.AddAttribute("ID", "test");output.RenderBeginTag(HtmlTextWriterTag.B);output.Write("Yo!");output.RenderEndTag();}

Basically all we are doing in the above code is overriding how the control renders its data. It will render a B tag with all the correct attributes.

And that is about it.

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)