The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Mar 2010»»
SMTWTFS
  12
3
456
7
8
9
10
111213
14151617181920
21222324252627
28293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Overlapping Server and embedded <% %> tags.

posted Wednesday, 20 July 2005

In ASP.Net, you can run into unexpected problems when combining embedded script and runat=server controls on the same object. Two resulting problems are:

  1. Your Html simply won't render (and you'll wonder why)
  2. You'll get an Html parse error, without it ever even hitting your code behind.

Let's look at a couple such snippets:

Okay: Embedded script doesn't overlap runat=server control.

<table border="1">
  <tr
>
    <td><%="Hello World" %></td
>
    <td><asp:Label id="Label1" runat="server">This is okay</asp:Label></td
>
  </tr
>
</
table>

Problem: This embedded script won't render because it is within the innerHtml of a WebControl (which is obviously runat=server).:

<tr>
  <td
>
    <asp:Label id="Label1" runat
="server">
      <%="Hello World"
%>
    </asp:Label
>
  </td
>
</
tr>

Okay: This does render (within the innerHtml of a runat=server Html control):

<tr>
  <td runat="server" id
="Td1">
    By<%="Hello World"
%>
  </td
>
</
tr>

Problem: This won't render, because it is within the attributes of a runat=server control:

<tr>
  <td runat="server" id="Td1" height='<%="60" %>'
>
    By
  </td
>
</
tr>

Big Problem: And this doesn't just render, it gives an Html parse error:

<tr>
  <td
>
    <asp:Label id="Label1" runat="server" Height='<%="30px"%>'>Label</asp:Label
>
  </td
>
</
tr>

The principles we see here are:

  1. Try to avoid combining embedded script and runat=server controls for the same object.
  2. While you may be able to get away with embedded script within the innerHtml of a runat=server HtmlControl, you:
    1. May run into difficulty putting it in the innerHtml of a WebControl (such as the Text of a Label).
    2. Should never put it in the attribute of the control itself. If you do need to put it in the attribute, then don't make the control runat=server.

 

links: digg this    technorati