Render ASP.NET TextBox as HTML5 Input type "Number" Render ASP.NET TextBox as HTML5 Input type "Number" asp.net asp.net

Render ASP.NET TextBox as HTML5 Input type "Number"


I had the same requirement for a mobile website using ASP.NET. After finding no good solution, I tried simply setting type="number" directly on the textbox. To my surprise, it worked! Incredulous, I created a simple test project to double-check. I ran this line of code in each .NET version:

<!-- this HTML tested in each .NET version --><asp:TextBox runat="server" type="number" />

Here are the results:

<!-- ASP.NET 2.0, 3.0, and 3.5 --><input name="ctl01" type="text" type="number" /><!-- ASP.NET 4.0 and 4.5 --><input name="ctl01" type="number" />

Bottom line: if you are using ASP.NET 4.0 or newer, just add type="number" to your textbox.


The TextMode property is used for that, e.g.

<asp:TextBox ID="uPhone" CssClass="formEntry" TextMode="Phone" ClientIDMode="Static" runat="server"></asp:TextBox>

might be rendered as

<input name="ctl00$ContentPlaceHolder1$uPhone" id="uPhone" class="formEntry" type="tel">

The textmodes in addition to [ MultiLine | Password | SingleLine ] were introduced some time after VS2010 - the documentation does not quickly tell me exactly when.


Override the base textbox control

public class HTML5TextBox : TextBox{.....protected override void Render(HtmlTextWriter writer){//Sth like the code below, you need do some research though writer.AddAttribute(HtmlTextWriterAttribute.Type,"Number"); writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_displayTXT"); writer.AddAttribute(HtmlTextWriterAttribute.Name,this.UniqueID + "t1"); writer.AddAttribute(HtmlTextWriterAttribute.Value,base.Text); writer.RenderBeginTag(HtmlTextWriterTag.Input);        writer.RenderEndTag(); }....}

Or you can check the one I just found at http://www.codeproject.com/Articles/68834/Enhanced-Textbox-Control