Question

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
}
Was it helpful?

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.

OTHER TIPS

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.

Add an expression in your page like this:

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

Add a property in the code-behind of your page:

protected string inputtypeCT;

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

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         this.inputtypeCT = "test"
    }
}
<input type="text" name="txt" value="<%= System.Web.HttpUtility.HtmlEncode(this.InputValue) %>" />

Add runat server

or use Asp controls like below

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

Also make sure that you used ClientIDMode="Static" for the naming of control to be in clinet as like server.

Enjoy!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top