Creating my own Web Server Hyperlink control - problems overriding the class attribute

1.1k Views Asked by At

I'm in the process of writing some web server controls to make working with basic jQuery UI themed controls and widgets easier. All I need to do at this stage is add some additional CSS classes into hyperlinks.

The code below is my web server control.

using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Fusion.UI.Controls
{
    [
    ToolboxData("<{0}:Hyperlink runat=\"server\"></{0}:Hyperlink>")
    ]
    public class Hyperlink : System.Web.UI.WebControls.HyperLink
    {
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "fg-button ui-state-default ui-corner-all");

            // Call underlying renderer
            base.AddAttributesToRender(writer);
        }
    }
}

This works fine and generates a hyperlink with the additional CSS classes. However if I also specify the CssClass it ends up creating a double class attribute:

<Fusion.UI:Hyperlink ID="Hyperlink1" runat="server" NavigateUrl="#" CssClass="ui-state-disabled" >Link</Fusion.UI:Hyperlink>

Which generates the following HTML:

<a class="fg-button ui-state-default ui-corner-all" id="ctl00_cphMainContent_Hyperlink1" class="ui-state-disabled" href="#">Link</a> 

Help! How can I stop this from happening?

2

There are 2 best solutions below

1
On BEST ANSWER

Assign the css class to the inherited CssClass property instead and let the base class handle the rendering.

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    CssClass = "fg-button ui-state-default ui-corner-all";
}
1
On

I think because of this line

base.AddAttributesToRender(writer);

It is creating a "class" attribute if the CssClass attribute has a value. Since the above code renders all the attributes specified in the control.

Try rendering the control yourself. This way your code control what attributes are rendered and in the case of css, you can check if it already has a value or not. If it has a value you can append it or discard it, whichever fits best to your needs.

Hope it helps.