views:

611

answers:

3

I am writing a bit of code to add a link tag to the head tag in the code behind... i.e.

HtmlGenericControl css = new HtmlGenericControl("link");

css.Attributes["rel"] = "Stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["href"] = String.Format("/Assets/CSS/{0}", cssFile);

to try and achieve something like...

<link rel="Stylesheet" type="text/css" href="/CSS/Blah.css" />

I am using the HtmlGenericControl to achieve this... the issue I am having is that the control ultimatly gets rendered as...

<link rel="Stylesheet" type="text/css" href="/CSS/Blah.css"></link>

I cant seem to find what I am missing to not render the additional </link>, I assumed it should be a property on the object.

Am I missing something or is this just not possible with this control?

Thanks

+3  A: 

I think you'd have to derive from HtmlGenericControl, and override the Render method.

You'll then be able to write out the "/>" yourself (or you can use HtmlTextWriter's SelfClosingTagEnd constant).

Edit: Here's an example (in VB)

Phil Jenkins
A: 

Alternatively you can use Page.ParseControl(string), which gives you a control with the same contents as the string you pass.

I'm actually doing this exact same thing in my current project. Of course it requires a reference to the current page, (the handler), but that shouldn't pose any problems.

The only caveat in this method, as I see it, is that you don't get any "OO"-approach for creating your control (eg. control.Attributes.Add("href", theValue") etc.)

TigerShark
A: 

I just created a solution for this, based on Ragaraths comments in another forum:

http://forums.asp.net/p/1537143/3737667.aspx

Override the HtmlGenericControl with this

protected override void Render(HtmlTextWriter writer)
{
    if (this.Controls.Count > 0)
        base.Render(writer); // render in normal way
    else
    {
        writer.Write(HtmlTextWriter.TagLeftChar + this.TagName); // render opening tag
        Attributes.Render(writer); // Add the attributes.  
        writer.Write(HtmlTextWriter.SelfClosingTagEnd); // render closing tag   
    }

    writer.Write(Environment.NewLine); // make it one per line
}
Tiggerito