0

Who would think so, but I actually need 3 levels of nested quotes in an ASP.NET WebForms page.

Here's what I have:

<img 
    src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
    onerror="this.onerror=null; this.src='SwissStyleguide/img/swiss.png';" 
    alt="Confederatio Helvetica" 
/>

Now, the first part, assigning a dynamically created URL to the src attribute works fine. The server resolves the given special URL and creates an absolute link for the client to fetch.

But the onerror handler is more tricky: since the src URL to the png image is already in an expression with double quotes, I can not invoke the ASP.NET ResolveClientUrl method, which strictly requires double quotes for the string argument.

I tried to do it like this (does not work!)

<img 
    src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
    onerror="this.onerror=null; this.src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.png"); %>';" 
    alt="Confederatio Helvetica" 
/>

But without much surprise, Visual Studio complains about this string. The only idea that comes to my mind is to use a string constant to avoid having the innermost quotes, but that seems very ugly.

Is there a way to escape or otherwise specify some or all of the quotes to make that work?

Note: I know about this question: When to use double or single quotes in JavaScript? but changing the quotes does not help in this case.

Marcel
  • 15,039
  • 20
  • 92
  • 150

2 Answers2

1

Well,... this turned out as an instance of the "<%$, <%@, <%=, <%# … what's the deal?" WebForms problem, answered perfectly here: https://stackoverflow.com/a/957321/79485

The solution is to use the equal sign after the percent sign and omit the trailing semicolon. Like this:

onerror="this.onerror=null; this.src='<%= ResolveClientUrl("~/SwissStyleguide/img/swiss.png") %>';" 

I'll leave the question and this answer here as a reminder of anyone tripping over this too.

Community
  • 1
  • 1
Marcel
  • 15,039
  • 20
  • 92
  • 150
1

How about placing the attributes from the code-behind instead?

.aspx

<img id="image" runat="server" alt="Confederatio Helvetica" /> 

.aspx.cs (Page_Load)

image.Attributes.Add("src", Page.ResolveUrl("~/SwissStyleguide/img/swiss.svg"));
image.Attributes.Add("onerror", "this.onerror=null; this.src='" +
    Page.ResolveUrl("~/SwissStyleguide/img/swiss.png") + "';";
abramlimpin
  • 5,027
  • 11
  • 58
  • 97
  • Yeah, this would work too. However, as I found out the quotes are not actually the problem. – Marcel Apr 21 '16 at 05:36
  • 1
    Server.MapPath would give an absolute Path on the server system, not one that resolves from the client. You should change that in your answer. – Marcel Apr 21 '16 at 05:37