views:

455

answers:

4

Setting value in html control in code behind without making server control

 <input type="text" name="txt" />
    <%--Pleas 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" />

Code behind

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
}

Thanks

+3  A: 

Elements that are not set runat="server" are considered plain text and collected into as few Literal objects as possible (one between each serverside control). I suppose if you really really wanted to, you could try to find the correct Literal (or maybe LiteralControl) object in Page.Controls, and modify it, but I'd definately recommend against it.

What's so terrible about setting it runat="server" ?

And yes, of course you can also use <%= %>. Embedded code blocks. They're evaluated at Render time, so it should be relatively safe to do so.

Arne Sostack
A: 

This answer comes from memory, so I apologize if it's slightly off.

What you can do is use an ASP.NET inline expression to set the value during the loading of the page.

First, add a property in the code-behind of your page.

protected string InputValue { get; set; }

In the Page_Load event, set the value of the property.

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

Finally, add an inline expression in your page markup like this:

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

This will let you set the value of the input element without making it a server-side tag.

Adam Maras
A: 

i am interested to hear and i am on same boat

Abu Hamzah
Though you have marked this as "community wiki" it is still not an answer to the question. There is an "add comment" link under each answer and the main question that allow you to comment on them, which is what this is, a comment. Please add these comments as comments rather than answers. Thanks.
Waleed Al-Balooshi
A: 

Blockquote What you can do is use an ASP.NET inline expression to set the value during the loading of the page.

First, add a property in the code-behind of your page.

protected string InputValue { get; set; } In the Page_Load event, set the value of the property.

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.InputValue = "something"; } } Finally, add an inline expression in your page markup like this:

" /> This will let you set the value of the input element without making it a server-side tag.

This works as dream thanks lot for the code

Siva