How can I use the button tag with ASP.NET?

Viewed 86039

I'd like to use the newer <button> tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as <input type="button">, is there any way to make a preexisting control render to <button>?

From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a <form>, but in ASP.NET it will be using the onclick event to fire __doPostBack anyway, so I don't think that this would be a problem.

Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided.


At first the <button runat="server"> solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all.

What do I need to do in order to override the render method and make it render what I want?


UPDATE

DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it.

First, there's a far easier way of overloading the TagName:

public ModernButton() : base(HtmlTextWriterTag.Button)
{
}

The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the <button> tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback.

The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this.

I have made progress on the rendering:

ModernButton.cs

This renders as a proper html <button> with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the Command event, but it doesn't fire.

When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the Command event in this case.

An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls?

7 Answers

Although you say that using the [button runat="server"] is not a good enough solution it is important to mention it - a lot of .NET programmers are afraid of using the "native" HTML tags...

Use:

<button id="btnSubmit" runat="server" class="myButton" 
    onserverclick="btnSubmit_Click">Hello</button>

This usually works perfectly fine and everybody is happy in my team.

I stumbled upon your question looking for the same exact thing. I ended up using Reflector to figure out how the ASP.NET Button control is actually rendered. It turns out to be really easy to change.

It really just comes down to overriding the TagName and TagKey properties of the Button class. After you've done that, you just need to make sure you render the contents of the button manually since the original Button class never had contents to render and the control will render a text-less button if you don't render the contents.

Update:

It's possible to make a few small modifications to the Button control through inheritance and still work fairly well. This solution eliminates the need to implement your own event handlers for OnCommand (although if you want to learn how to do that I can show you how that is handled). It also fixes the issue of submitting a value that has markup in it, except for IE probably. I'm still not sure how to fix IE's poor implementation of the Button tag though. That may just be a truly technical limitation that is impossible to work around...

[ParseChildren(false)]
[PersistChildren(true)]
public class ModernButton : Button
{
    protected override string TagName
    {
        get { return "button"; }
    }

    protected override HtmlTextWriterTag TagKey
    {
        get { return HtmlTextWriterTag.Button; }
    }

    // Create a new implementation of the Text property which
    // will be ignored by the parent class, giving us the freedom
    // to use this property as we please.
    public new string Text
    {
        get { return ViewState["NewText"] as string; }
        set { ViewState["NewText"] = HttpUtility.HtmlDecode(value); }
    }

    protected override void OnPreRender(System.EventArgs e)
    {
        base.OnPreRender(e);
        // I wasn't sure what the best way to handle 'Text' would
        // be. Text is treated as another control which gets added
        // to the end of the button's control collection in this 
        //implementation
        LiteralControl lc = new LiteralControl(this.Text);
        Controls.Add(lc);

        // Add a value for base.Text for the parent class
        // If the following line is omitted, the 'value' 
        // attribute will be blank upon rendering
        base.Text = UniqueID;
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        RenderChildren(writer);
    }
}

To use this control, you have a few options. One is to place controls directly into the ASP markup.

<uc:ModernButton runat="server" 
        ID="btnLogin" 
        OnClick="btnLogin_Click" 
        Text="Purplemonkeydishwasher">
    <img src="../someUrl/img.gif" alt="img" />
    <asp:Label ID="Label1" runat="server" Text="Login" />
</uc:ModernButton>

You can also add the controls to the control collection of the button in your code-behind.

// This code probably won't work too well "as is"
// since there is nothing being defined about these
// controls, but you get the idea.
btnLogin.Controls.Add(new Label());
btnLogin.Controls.Add(new Table());

I don't know how well a combination of both options works as I haven't tested that.

The only downside to this control right now is that I don't think it will remember your controls across PostBacks. I haven't tested this so it may already work, but I doubt it does. You'll need to add some ViewState management code for sub-controls to be handled across PostBacks I think, however this probably isn't an issue for you. Adding ViewState support shouldn't be terribly hard to do, although if needed that can easily be added.

You could make a new control, inheriting from Button, and override the render method, or use a .browser file to override all Buttons in the site, similar to the way the CSS Friendly stuff works for the TreeView control etc.

I would go with a LinkButton and style it with CSS as appropriate.

I've been struggling all day with this -- my custom <button/> generated control not working:

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

What happens is that .Net adds a name attribute:

<button type="submit" name="ctl02" value="Content" class="btn ">
   <span>Content</span>
</button>

The name attribute throws the server error when using IE 6 and IE 7. Everything works fine in other browsers (Opera, IE 8, Firefox, Safari).

The cure is to hack away that name attribute. Still I haven't figured that out.

Related