0

Agree my question is duplicate of this one and accepted answer works for me too. Let me clarify why.

When I have <%= in head it gives error.

When I have <%= in body it works.

When I have <%# in head it works.

I am just curious to know the reason for all three scenarios.

Additionally I created test project to emulate the issue but in that case all three situation works.

My page is too big and I am unable to decide what code to paste.

Community
  • 1
  • 1
Imad
  • 7,126
  • 12
  • 55
  • 112

1 Answers1

0

<%= %> is in fact doing Response.Write, which is literally writing symbols to the response. To the final markup that is.

Now notice that your head tag has this attribute runat="server". That makes it a server control. That is, this is not a final markup, and but rather a control that will output some markup to response during the control rendering stage. You cannot call Response.Write on this control, because it is not a final markup yet.

For the same reason it would work/not work in the body of the page. If you put it somewhere in plain markup it would work no problem:

<div><%= "Blah" %></div> <%-- works! --%>

But as soon as it appears inside anything with runat="server" you'll get an error

<div runat="server><%= "Blah" %></div> <%-- error! --%>
<asp:Panel runat="server"><%= "Blah" %></asp:Panel> <%-- error! --%>

Now <%# %> is a different beast. This is a data binding markup, something that is being evaluated when the server side control is being data bound. Thus is makes no sense (and is invalid) inside plain markup, and can be used whenever your control is bound to some data. Using it with header is not very common, use cases with GridView or Repeater are the most typical ones that come to mind.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • I have head in master page, using `<%=` in head. But few content pages are having no problem with it but few are having. – Imad Sep 26 '16 at 12:47
  • @Imad, please take another look at the answer. It does not matter if this is a master page or not. It only matters if you are using it inside server-side control or in the plain markup – Andrei Sep 26 '16 at 12:49
  • I just tried to tell you that head tag which in server control is used across multiple pages and it is not giving problem at all the places. – Imad Sep 26 '16 at 12:58
  • Very strange. How are these pages different? Perhaps some of them overwrite content of the header? Please add details to your question then – Andrei Sep 26 '16 at 13:24