views:

1337

answers:

5

I am using ASP.NET webforms on the .NET 3.5 framework. How can I achieve a custom attribute in the HTML tag such as:

<HTML lang="en">

I want to achieve this in the code behind on a common inherited base page. The attribute value would dynamically set based on a session value everytime a page is loaded.

Late addition: I want to achieve this without any ASP page changes to script tags if possible

+1  A: 

in html:

<HTML lang="<%=myLang%>">

In codebehind:

protected string myLang = "en"
Alex Reitbort
Thanks alex, I was hoping to avoid ASP page changes as there are 100's to change. I have edited and clarified the question now.
nick_alot
+1  A: 

Solution 1:

<HTML lang="<%= PageLanguage %>">

where PageLanguage is virtual protected property of your base page. The value is overriden in the derrived pages (from what I understand you need to to change this on page level?)

Solution 2:

Hack-it: the Page.Controls[0] contain a text that contains the html tag. A simple replace on page prerender event would do it.

Aleris
+5  A: 

The suggested solution:

<HTML lang="<%= PageLanguage %>">

works fine. There's another alternative that Aleris is onto but hasn't got quite right. If you add the runat="server" attribute to the HTML tag, it will be parsed to a server-side HtmlGenericControl and be available in the Controls collection. Further, if you add an id attribute, you will have a variable in the code behind to access it directly, thus:

<html runat="server" id="html">

in codebehind:

html.Attributes["lang"] = "en";

Note: this is true for any HTML tag in your page.

Edit: I see now Aleris did get it right - he refers to 'a text' (actually, a LiteralControl) in the Controls collection that contains the html tag (along with the doctype and anything else up to the first server tag). You could manipulate this text, of course, and it would be (as he says) a hack - but it would restrict the changes to code-behind only.

Tor Haugen
A: 

I use AddParsedSubObject method of Page class.

You can get control object by AddParsedSubObject method parameter in parsing process.

Override this method such as...

protected override void AddParsedSubObject(object control)
{
    if (obj is LiteralControl) 
    {
        String html = (obj as LiteralControl).Text;
        if (Regex.IsMatch(html, "<html[^>]*>") == true)
        {
            String newhtml = Regex.Replace(html, "<html[^>]*>", "<html lang=\"en\">");
            base.AddParsedSubObject(new LiteralControl(newhtml));
        }
    }
}

You can customize your output of html tag and also other tag. Hope your help!!

Higty
A: 

If you're just trying to do internationalisation of your website, may as well use the in-built systems provided by .net (cause they are beautiful). Is that what you want to do? Or something else?

Noon Silk