Tuesday, July 19, 2005

Overlapping Server and embedded <% %> tags.

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/overlapping_server_and_embedded_lt_gt_tags.htm]

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 okayasp: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"%>'>Labelasp: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.

 

No comments:

Post a Comment