Insights and discoveries
from deep in the weeds
Outsharked

Saturday, December 18, 2010

<% Eval %>, html, apostrophes, quotes

Welcome to Outsharked. Who am I, what is the purpose of this blog? What is the nature of the universe? These questions will be answered later. For now, I just wanted to make a note of a slightly annoying problem which has a simple, yet difficult to find, solution.

In <%# Eval() #> statements in asp.net, how to use quotes and double quotes when it's inside a tag element? The example below shows the solution:

<td class="DataListRow">
  <asp:HyperLink runat="server" 
    NavigateUrl='<%# Eval("RowID","return confirm(&#39;Load document with ID {0}?&#39;);") %>' 
    Text="View"> 
  </asp:HyperLink>
</td>

This comes from a ListView and RowID is a key. The code needs to generate javascript to show a dialog with the unique row ID.

The answer is twofold.

One: enclose your tag element in single-quotes instead of double-quotes. This lets you use the double-quotes inside it for the eval. Then use &#39; to render a single-quote.

But what if I need double-quotes inside there too?

Now it's getting a little hairy. When ASP.NET processes this thing, it's going to actually take the formatted HTML inside the second Eval parameter to use as a format string. Then, that will be again processed when the Format function runs.

So you need to make sure that the HTML renders as a valid format string. Here's an example:

<td class="DataListRow">
  <asp:HyperLink runat="server" 
  NavigateUrl='<%# Eval("DocumentTitle",
    "confirm(&#39;Delete document with title \&quot;{0}\&quot;?&#39;);") %>' 
    Text="View"> 
  </asp:HyperLink>
</td>

The \&quot; will render as \", which is the correct format for asp.net to parse into just a double-quote in a string. Assuming all goes well, if DocumentTitle was "Some Document", you'll get a dialog that just says:

Delete document with title "Some Document"?

No comments:

Post a Comment