Visual Studio freaks out when your HTML contains nested
quotes. Roy's
solution (using single quotes for the attribute and double quotes for the
databinder or function arguments)
works unless you need to nest quotes, which
occurs if you're including a Javascript call in a databinding statement:
<asp:TemplateColumn>
<ItemTemplate>
<a href="javascript:showPopup('\Popups\Edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem,"itemID")%>')">edit</a>
</ItemTemplate>
</asp:TemplateColumn>
The problem here is that you need
quotes around your href attribute, quotes around your javascript function
argument, and quotes around your DataBinder.Eval string
parameter.
Tim sums it up pretty will here, but you're pretty much stuck with either
"Quote values differently inside a '<% ..."value"... %>'
block." or "Place quotes around a '<%
%>' block used as an atribute value or within a SELECT element." I
haven't seen a good discussion on how to handle this well, so here's what I've
come up with - please recommend something else if you've got a better
solution.
We need a third quote, right? Well, one common solution is to use
\u0022 - the VS UI doesn't see it as a quote and doesn't get
confused, but the ASP.NET rendering engine writes it out as a quote:
<asp:TemplateColumn>
<ItemTemplate>
<a href ="javascript:showPopup(\u0022\Popups\Edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem,"itemID")%>\u0022)">
edit< /a>
</ItemTemplate>
</asp:TemplateColumn>
A better solution is to just escape
the quote with a backslash (\"). The VS IDE handles that just
fine:
<asp:TemplateColumn>
<ItemTemplate>
<a href ="javascript:showPopup(\"\Popups\Edit.aspx?ID=<%# DataBinder.Eval(Container.DataItem,"itemID")%>\")">
edit< /a>
</ItemTemplate>
</asp:TemplateColumn>
Another solution is to use code behind to actually
construct the links. I normally wouldn't use that unless there was a good
amount of formatting, and even then you can get away from that with a format
string in the DataBinder.Eval call. I usually see people recommend
one-off functions for that kind of thing, but I prefer using something more
generic. The following function will work in a page code behind, but could be made a static function and placed in a code library class:
protected string BuildJavascriptLink(string format, params string[] input)
{
format = format.Replace("{quote}","\"");
string retval = string.Format(format,input);
retval = retval.Replace("'","\"");
return retval;
}
Now we could reference it in the code front with something like this:
<a href='<%# BuildJavascriptLink("javascript:showPopUp({quote}/PopUps/{0}{1}{quote},{2},{3})","StreetLevelMap.aspx?ID=",Convert.ToString(DataBinder.Eval(Container.DataItem,"Entity_ID")),"600","450") %>'>Street Map</a>