Search code examples
c#asp.netcustom-server-controls

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


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?


Solution

  • 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";
    }