I\'d like to use the newer tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button.
This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls.
As per Bootstrap documentation, the desired markup is as follows:
I needed this markup to be rendered by a server control, so I set out to find options.
This would be the first logical step, but —as this question explains— Button renders an element instead of , so adding inner HTML is not possible.
Source
Search
Output
Search
Pros
Command event; CommandName and CommandArgument propertiesCons
Source
Result
Pros
elementCons
Command event; no CommandName or CommandArgument propertiesServerClick eventAt this point it is clear that none of the built-in controls seem suitable, so the next logical step is try and modify them to achieve the desired functionality.
NOTE: This is based on Dan's code, so all credit goes to him.
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ModernControls
{
[ParseChildren]
public class ModernButton : Button
{
public new string Text
{
get { return (string)ViewState["NewText"] ?? ""; }
set { ViewState["NewText"] = value; }
}
public string Value
{
get { return base.Text; }
set { base.Text = value; }
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Button; }
}
protected override void AddParsedSubObject(object obj)
{
var literal = obj as LiteralControl;
if (literal == null) return;
Text = literal.Text;
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(Text);
}
}
}
I have stripped the class down to the bare minimum, and refactored it to achieve the same functionality with as little code as possible. I also added a couple of improvements. Namely:
PersistChildren attribute (seems unnecessary)TagName override (seems unnecessary)Text (base class already handles this)OnPreRender intact; override AddParsedSubObject instead (simpler)RenderContents overrideValue property (see below)using directivesThe Value property simply accesses the old Text property. This is because the native Button control renders a value attribute anyway (with Text as its value). Since value is a valid attribute of the element, I decided to include a property for it.
Source
<%@ Register TagPrefix="mc" Namespace="ModernControls" %>
Search
Output
Pros
elementCommand event; CommandName and CommandArgument propertiesCons