简体   繁体   中英

<%= %> tag not working to display content inside an ASP Label control

Noob question. Why does this not work into my .aspx file?

<body> 
<asp:Label ID="Label1" runat="server" Text='<%=System.DateTime.Today.Day.ToString()%>' ></asp:Label>
</body>

It does display the <%=System.DateTime.Today.Day.ToString()%> string which is obviously not what I want.

Same result if I try to display the content of a code behind variable:

<asp:Label ID="label" runat="server" Text='<%= versionNumber %>' >

versionNumber being properly instanced and set into the code behind.

You cannot mix server controls with code blocks.

There are two ways to work around that limitation:

  • Just use <%=System.DateTime.Today.Day.ToString()%> without a Label around it
  • Use codebehind to set Label1.Text = System.DateTime.Today.Day.ToString();

The first way will display the date to the user, but you cannot further change it from codebehind. The second way does enable you to alter the text from codebehind.

It is true you can't mix server controls with Code blocks,

If its compulsory for you to use Server side control, and you don't even want to set value from code behind then you can go for this solution.

<asp:Label ID="Label1" runat="server"><%=System.DateTime.Today.Day.ToString() %></asp:Label>

Similarly you can use code behind variable as follows ,

<asp:Label ID="Label1" runat="server"><%=versionNumber %></asp:Label>

If you really want to use a asp:Label

Use it as follows:

<asp:Label ID="Label1" runat="server"><%=System.DateTime.Today.Day.ToString() %></asp:Label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM