是否可以写这样的东西?
<input class="form-control" id="name" name="name"
placeholder='<asp:Label runat="server" ID="lblFormName"></asp:Label>' type="text" required autofocus />
答案 0 :(得分:2)
您想为HTML元素的某个属性分配一些值吗?
<asp:HiddenField runat="server" ID="lblFormName" />
<input class="form-control" id="name" name="name" placeholder='<%# lblFormName.Value %>' ...
然后从CodeBehind传递lblFormName.Value
。
答案 1 :(得分:2)
您无法在纯HTML页面中声明单个ASP.NET控件。它必须是由服务器处理的ASP.NET页面(aspx)。
答案 2 :(得分:2)
您可以使用本机TextBox控件:
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder" />
额外属性(不属于TextBox类的属性)将按原样呈现:
Html结果:
<input name="ctl00$MainContent$name"
type="text"
id="MainContent_name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
如果生成的ID必须是显式的,您可以添加CliendIDMode="Static"
:
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder"
ClientIDMode="Static" />
结果:
<input name="ctl00$MainContent$name"
type="text"
id="name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
更好的方法是扩展文本框类:
using System.Web.UI.WebControls;
namespace WebApplication1.Controls
{
public class TextBoxEx : TextBox
{
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
if (AutoFocus) writer.AddAttribute("autofocus", "autofocus");
if (Required) writer.AddAttribute("required", "required");
if (!string.IsNullOrEmpty(PlaceHolder)) writer.AddAttribute("placeholder", PlaceHolder);
base.AddAttributesToRender(writer);
}
public string PlaceHolder
{
get {
var obj = ViewState["PlaceHolder"];
return obj != null ? (string)obj : default(string);
}
set { ViewState["PlaceHolder"] = value; }
}
public bool AutoFocus
{
get {
var obj = ViewState["AutoFocus"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["AutoFocus"] = value; }
}
public bool Required
{
get {
var obj = ViewState["Required"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["Required"] = value; }
}
}
}
然后您可以注册并使用控件:
<%@ Register Assembly="WebApplication1" TagPrefix="local" Namespace="WebApplication1.Controls" %>
....
<local:TextBoxEx runat="server" required="true" autofocus="true" PlaceHolder="my placeholder" />