Add HTML5 placeholder text to a textbox .net

I have a standard input:

<asp:TextBox type="text" runat="server" id="txtSearchTerm" />

I’d like to have this render with a dynamic HTML5 placeholder. Something like:
'Code Behind
txtSearchTerm.**placeholder** = "Search " + Site.Name

So that it outputs the following HTML:
<input type="text" runat="server" id="txtSearchTerm" 
placeholder="Search Site #1" />

where Site.Name = “Site #1”.

txtSearchTerm.placeholder is not a property. I have it set to text and then run javascript to show/hide on focus BUT I would much rather just use the HTML5 placeholder value. How can I render this?

Please no JS/client side solutions.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could use the Attributes collection. So you would have something like

txtSearchTerm.Attributes.Add("placeholder", "Search" + Site.Name);

txtSearchTerm.Attributes["placeholder"] = "Search" + Site.Name; // or Attributes("placeholder") if you're using

And if you’re using resources for localization/translation:
txtSearchTerm.Attributes["placeholder"] = GetLocalResourceObject("YourLocalResourceName").ToString();

Method 2

Because I find it annoying/tiresome to add all the placeholders from the code behind. You can create a new TextBox Class that inherits the WebControls TextBox and then you can add the placeholder from the CodeBehind or from the HTML Side.

TextBox.cs (Placed in Project/Controls/)

namespace Project.Controls
    public class TextBox : System.Web.UI.WebControls.TextBox
        public string PlaceHolder { get; set; }

        protected override void OnLoad(EventArgs e)
                this.Attributes.Add("placeholder", PlaceHolder);


Register Control In the Web.Config:
        <add tagPrefix="ext" assembly="Project" namespace="Project.Controls" />

(use whatever tag prefix you want)


<ext:TextBox runat="server" id="SomeId" PlaceHolder="This is a PlaceHolder" />

or from the code behind
SomeId.PlaceHolder="This is a PlaceHolder";

Method 3

I just put placeholder property in HTML code and works:

<asp:TextBox placeholder="hola mundo" ID="some_id" runat="server"/>

Method 4

There is also the TextBoxWatermark extender included in Microsoft’s Ajax Control toolkit. It’s not HTML5, but it’s backwards compatible (I believe).

<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
    WatermarkText="Type First Name Here"
    WatermarkCssClass="watermarked" />

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x