Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use <%= ... %> to set a control property in ASP.NET?

Tags:

asp.net

<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%=Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>

The code above does not work. I can set the MaxLength property of the textbox in the code behind but i rather not. Is there away I can set the MaxLength property in the front-end code as above?

like image 608
burnt1ce Avatar asked Sep 01 '09 14:09

burnt1ce


2 Answers

You could use DataBinding:

<asp:TextBox 
    ID="tbName" 
    CssClass="formField" 
    MaxLength="<%# Constants.MaxCharacterLengthOfGameName %>" 
    runat="server">
</asp:TextBox>

and in your code behind Page_Load call:

tbName.DataBind(); 

or directly databind the page:

this.DataBind();
like image 60
Darin Dimitrov Avatar answered Oct 14 '22 02:10

Darin Dimitrov


The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values of Web control properties. In other words, you cannot have markup like the following:

<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" />

Source: http://aspnet.4guysfromrolla.com/articles/022509-1.aspx

like image 25
Ropstah Avatar answered Oct 14 '22 01:10

Ropstah