Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why <%= %> works in one situation but not in another

Tags:

asp.net

This is stemming from a bad answer I gave last night. The curiosity as to why one method works and not the other is bugging me and I'm hoping someone smarter than me can give me the proper explanation (or point me to the documentation) of why the following behavior is as it is.

Given the following code-behind:

protected string GetMyText(string input)
{
  return "Hello " + HttpUtility.HtmlEncode(input);
}

Why does this work

 <asp:Label ID="Label1" runat="server"><%= GetMyText("LabelText") %></asp:Label>

but this does not

<asp:Label ID="Label1" runat="server" Text='<%= GetMyText("LabelText") %>' />

Edit - added

At the risk of having my original dumb answer downvoted more times, here's the link to the original question, since some of the answers I'm getting now were already covered in that question.

Why can't I set the asp:Label Text property by calling a method in the aspx file?

like image 209
David Avatar asked Oct 07 '09 13:10

David


2 Answers

Using <%= %> is equal to putting Response.Write("") in your page. When doing this:

<asp:Label ID="Label1" runat="server"><%= GetMyText("LabelText") %></asp:Label>

The ASP.NET processor evaluates the control, then when rendering, it outputs the control's contents & calls Response.Write where it sees <%=.

In this example:

<asp:Label ID="Label1" runat="server" Text='<%= GetMyText("LabelText") %>' />

You can't use Response.Write("") on a Text attribute because it does not return a string. It writes its output to the response buffer and returns void.

If you want to use the server tag syntax in ASP.NET markup you need to use <%# %>. This combination of markup data binds the value in the tags. To make this work, you'll then need to call DataBind() in your page's Load() method for it to work.

like image 110
Dan Herbert Avatar answered Sep 28 '22 08:09

Dan Herbert


Because they are both server side instructions - the second piece of code is equivalent to:

<asp:Label ID="Label1" runat="server" Text='Response.Write(GetMyText("LabelText"))' />
like image 30
Mark Bell Avatar answered Sep 28 '22 08:09

Mark Bell