如何在asp:文本框中添加提示

use*_*849 96 css asp.net html5 hint placeholder

如何在asp:TextBox中放置一个提示/占位符?当我说一个提示时,我的意思是一些文字在用户点击它时会消失.有没有办法使用html/css实现相同的目标?

Lin*_*ell 187

placeholder属性

你正在寻找placeholder属性.像使用ASP.net控件中的任何其他属性一样使用它:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>
Run Code Online (Sandbox Code Playgroud)

不要担心您的IDE(即Visual Studio)可能不知道该属性.未在ASP.net中注册的属性将按原样传递和呈现.所以上面的代码(基本上)呈现给:

<input type="text" placeholder="hint"/>
Run Code Online (Sandbox Code Playgroud)

placeholder在资源中使用

将提示应用于控件的一种好方法是使用资源.这样您就可以拥有本地化提示.假设您有一个index.aspx文件,您的App_LocalResources/index.aspx.resx文件包含

<data name="WithHint.placeholder">
    <value>hint</value>
</data>
Run Code Online (Sandbox Code Playgroud)

你的控制看起来像

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>
Run Code Online (Sandbox Code Playgroud)

渲染结果看起来与上一章中的结果相同.

在代码后面添加属性

像任何其他属性一样,您可以添加placeholderAttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,资源技巧`"WithHint.placeholder"` 对我不起作用。 (3认同)

小智 60

就像这样写:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>
Run Code Online (Sandbox Code Playgroud)


Shr*_*abh 18

 <asp:TextBox runat="server" ID="txtPassword" placeholder="Password">
Run Code Online (Sandbox Code Playgroud)

这可能会因为Intellisence没有显示占位符而有时会觉得它无法正常工作

  • 关于Intellisence的说明非常有用! (8认同)

Shi*_*mas 7

从代码隐藏中添加占位符属性:

txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name);
Run Code Online (Sandbox Code Playgroud)

要么

txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name;
Run Code Online (Sandbox Code Playgroud)

从aspx页面添加占位符属性

<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" />
Run Code Online (Sandbox Code Playgroud)

要么

<input type="text" id="txtFilterTerm" placeholder="Filter"/>
Run Code Online (Sandbox Code Playgroud)