asp.net: how to make asp:button render a button tagname with type=submit

March 25th, 2011 admin Posted in asp.net, c#, development, Uncategorized | No Comments »

Sometimes when I try to style the asp:button I get pretty frustrated because it has its limitations as it's not a container so you can't add any elements inside it. The real question is - why did Microsoft not make it possible to change the asp:button behaviour so it would be the option which tag you want to render? [sigh]
There are some articles in the internet saying how you can fix that by using web control adaptors or even javascript.
But what I really wanted is to have a different control that would render what I wanted it to. So I came up with the solution of extending the standard asp:button and overriding a couple of methods in it. The code is below. It's very simple and seems to work for me.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
 
namespace MyControls
{
    /// Class extending Button, but rendering button type='submit'
    public class ButtonSubmit : Button
    {
        public ButtonSubmit()
            : base()
        { }
 
        public string Value
        {
            get
            {
                string str = (string)ViewState["Value"];
                if (str != null)
                {
                    return str;
                }
                return string.Empty;
            }
            set { ViewState["Value"] = value; }
        }
 
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Button);
        }
 
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (HasControls())
                base.RenderChildren(writer);
            else
                writer.Write(Text);
        }
 
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            // substitute "text" with "value" because the base class uses "text" for "value"
            string strText = Text;
            Text = Value;
            base.AddAttributesToRender(writer);
            Text = strText;
        }
    }
}
 

Leave a Reply

You must be logged in to post a comment.