Search code examples
asp.nethtmlcontrols

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


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

 <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" />

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
}

Solution

  • 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.