views:

232

answers:

3

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?

+1  A: 

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.

iHeartDucks
Rendering the control yourself isn't really needed just to solve this particular problem. The HyperLink base class can provide the needed rendering capability in this case, once you have set up the necessary data in the properties.
PHeiberg
+2  A: 

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";
}
PHeiberg
Needs to be:protected override void OnPreRender(EventArgs e){ CssClass = "fg-button ui-state-default ui-corner-all " + CssClass; base.OnPreRender(e);}But thanks for the answer I was looking for :)
Peter Bridger
A: 

Θέλω να καμω μια δικη μου ιστοσελιδα και δεν ξερω πως μπορει να με βοηθήσει καποιοσ σασ παρακαλω

dimitris