4

I need to add some attributes (http://www.w3.org/International/questions/qa-http-and-lang) to the tag in an ASP.NET Page object. Note: I cannot do this in a declarative manner and have to use the server side object model to do it. Any ideas?

To add some additional information: I need to do this within the ASP.NET Page rendering life cycle. I need to add the attribute to the root element in the page.

Slappy
  • 4,042
  • 2
  • 29
  • 41

2 Answers2

5

You should see the following MSDN article:

It looks simple enough:

myButton.Attributes.Add("myattribute", "myValue");

Update: You can do this to any element that has an id and is set with runat="server", for example:

<html id="htmlTag" runat="server" ...

this.htmlTag.Attributes.Add("myAttribute", "myValue");
Justin
  • 84,773
  • 49
  • 224
  • 367
  • 1
    This is along the lines of what I am looking for except I need to add it to the (root) tag, which I cant see exposed as a control (unless I am missing something) – Slappy Feb 28 '11 at 02:08
  • 2
    @Slappy add `runat="server"` to the HTML tag and give it an id - that should do the trick. – Justin Feb 28 '11 at 02:10
  • @Kragen is correct with the previous comment. I do this all the time to set the class for our designers. It should apply to the HTML tag too. – Mike Cole Feb 28 '11 at 02:12
  • Sadly I dont have access to the declarative. But thanks this is the closet answer and will probably work for someone else – Slappy Feb 28 '11 at 02:19
  • 1
    @Slappy In that case you might want to try overriding the Render method of the page and using something like the HTML agility pack to directly intercept and modify the output html. See [get HTML of current page without ViewState ASP.Net](http://stackoverflow.com/questions/531631/get-html-of-current-page-without-viewstate-asp-net) for a kind-of example. Its not really within the ASP.Net page lifecycle, but I'm not aware of many other ways of doing this. – Justin Feb 28 '11 at 02:38
  • @Slappy The other way I can think of would be to loop through the Controls collection until you find the `LiteralControl` containing the html tag, and directly modify the `Text` element of that control (This is probably even more of a hack than overriding the Render method) – Justin Feb 28 '11 at 02:42
0

I think the HTML Agility Pack will give you what you're looking for.

Robert Williams
  • 1,340
  • 9
  • 12
  • I don't think this will work as I am still within the rendering process and have no hooks to the raw html output. – Slappy Feb 28 '11 at 02:06
  • Gotcha. If you're still within your rendering process then I'd use Kragen's method of adding the runat="server" to your HTML tag. – Robert Williams Feb 28 '11 at 02:15