2013-04-05 231 views
69

如何在asp:TextBox中添加提示/佔位符?當我說一個提示時,我的意思是一些文字在用戶點擊時會消失。有沒有辦法使用HTML/CSS實現相同?如何在asp:TextBox中添加提示

+2

您支持哪些瀏覽器? HTML5瀏覽器支持文本框的「佔位符」屬性。 – rikitikitik 2013-04-05 00:32:51

+0

http://stackoverflow.com/questions/35501114/in-asp-net-unable-to-save-textboxes-if-the-text-is-given-in-between-and – Sachin 2016-02-19 08:58:50

回答

135

placeholder屬性

您正在尋找的placeholder屬性。使用它像你的ASP.net控件中任何其他屬性:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/> 

不要理會你的IDE(即Visual Studio中)也許不知道屬性。未通過ASP.net註冊的屬性將按原樣傳遞並呈現。所以上面的代碼(基本上)呈現到:

<input type="text" placeholder="hint"/> 

在資源

施加提示控制使用resources的精細方式使用placeholder。這樣你可能有本地化的提示。比方說,你有一個的Index.aspx文件,您App_LocalResources文件/ index.aspx.resx文件包含

<data name="WithHint.placeholder"> 
    <value>hint</value> 
</data> 

和你的控制看起來像

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/> 

渲染的結果看起來是一樣的作爲上面章節中的內容。在代碼

添加屬性後面

其它的屬性一樣,你可以在placeholder添加到AttributeCollection

txtWithHint.Attributes.Add("placeholder", "hint"); 
58

就這樣寫:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox> 
14
<asp:TextBox runat="server" ID="txtPassword" placeholder="Password"> 

這將工作你可能會有一段時間覺得它不工作,因爲Intellisence沒有顯示荷蘭國際集團佔位

+5

有關Intellisence的說明很有幫助! – 2015-08-31 07:28:45

0
asp:TextBox ID="txtName" placeholder="any text here" 
4

添加佔位符從代碼隱藏屬性:

txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name); 

或者

txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name; 

添加佔位符從ASPX頁面屬性

<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" /> 

<input type="text" id="txtFilterTerm" placeholder="Filter"/>