Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET TextBox - is it possible to initialize text attribute with in line code <% %>

Tags:

c#

asp.net

vb.net


I need to initialize the text attribute of the text box element with a property from some where else when actually I can simply do this from code but it will be much more convenient if it possible to do it like this:

<asp:TextBox runat="server" Text="<%= new ContextItem("title").Value %>" />

Unfortunately the above can't be done..
The issue is that this text box element repeats it self several times in the page and my question is:

Are there any suggestions how to make it cleaner then to write it again and again in the code behind?
Thank, Adler

like image 557
Adler Avatar asked Jul 26 '11 20:07

Adler


1 Answers

OK so the basic problem here is that if you use an inline expression you can NOT use it to set a property of a server-side control outside of a binding context (using a binding expression). I have inferred that this is probably because of the timing of the evaluation of these inline expressions. You can, however, render client-side markup in this way. If you want to keep the functionality purely in your aspx file, this is the way to do it.

Edit: Based on input from Justin Keyes, it appears it IS possible to use a binding expression to set the property. You need to manually invoke Page.DataBind() to trigger the textbox to evaluate the expression (see answer below).

For instance this:

<asp:Label ID="lbl" runat="server" Text="<%= Now.ToShortDateString() %>"  />

Will produce this output:

<%= Now.ToShortDateString() %>

On the other hand this:

<%= "<span>" & Now.ToShortDateString() & "</span>"%>

Will produce this output:

7/27/2011

The "normal" way to solve this problem is just to set the Label.Text properties in a Page.Load event handler or another appropriate event handler depending on your needs, as below. This is the way I believe most people would prefer to do it, and is most easily understandable in my opinion.

Markup:

<asp:Label ID="lbl" runat="server" />

Code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    lbl.Text = Now.ToShortDateString()
End Sub
like image 118
pseudocoder Avatar answered Sep 28 '22 07:09

pseudocoder