2010-02-24 31 views
5

设定值后面未做服务器控件设定值后面未做服务器控件在代码的HTML控件

<input type="text" name="txt" /> 
    <!--Please note I don't want put 'runat="server"' here to get the control in code behind--> 
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 

后面的代码:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     //If I want to initlize some value in input, how can I set here 
    } 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
    Request["txt"] // Here I am getting the value of input 
} 

回答

11

元素未设置RUNAT =“server”被认为是纯文本并被收集到尽可能少的Literal对象(每个服务器端控件之间的一个)。我想,如果你真的很想,你可以尝试在Page.Controls中找到正确的Literal(或可能是LiteralControl)对象,并修改它,但我肯定会推荐它。

什么是那么可怕有关设置它的Runat =“服务器”?

是的,当然你也可以使用<%=%>。 Embedded code blocks。它们在渲染时进行评估,因此它应该相对安全。

+3

runat =“server”似乎也将名称更改为例如“ctl00 $ Main $ Something”实际上打破了应该到别处的表单(例如PayPal)的整个帖子。 – Johncl 2012-09-17 13:55:49

26

这个答案来自于内存,所以我道歉,如果这是稍微偏离。

你可以做的是使用ASP.NET内嵌式网页的加载过程中设置的值。

首先,在页面的代码隐藏中添加一个属性。

protected string InputValue { get; set; } 

Page_Load事件中,设置该属性的值。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     this.InputValue = "something"; 
    } 
} 

最后,在你的网页标记添加内嵌表达式是这样的:

<input type="text" name="txt" value="<%= this.InputValue %>" /> 

这将让你设置input元素的值没有使它的服务器端代码。

1
<input type="text" name="txt" value="<%= System.Web.HttpUtility.HtmlEncode(this.InputValue) %>" /> 
2

在页面中添加一个表达式是这样的:

<input class="field" id="locality" name="loc" value="<%= this.inputtypeCT %>"/> 

在你的页面的代码隐藏添加的属性:

protected string inputtypeCT; 

在Page_Load事件中,设定值的物业:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     this.inputtypeCT = "test" 
    } 
} 
0

RUNAT服务器

或使用ASP控制像下面

<asp:TextBox type="text" runat="server" class="demoHeaders" id="datepicker" ClientIDMode="Static" Text=""/> 

另外,还要确保你使用的ClientIDMode =“静态”控制的命名是在客户为例像服务器。

享受!

相关问题