Marcel
Marcel

Reputation: 15732

Nesting quotes in HTML > JavaScript > WebForms or how to call a .NET method in a JavaScript method

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.

Upvotes: 0

Views: 142

Answers (2)

abramlimpin
abramlimpin

Reputation: 5077

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") + "';";

Upvotes: 1

Marcel
Marcel

Reputation: 15732

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.

Upvotes: 1

Related Questions