Wednesday, January 7, 2009

HTML and Inline $SPUrl Gotcha

When mixing html tags and SharePoint controls, like in a custom master page or page layout for example, it's easy to make the following mistake:
<img src="<% $SPUrl:~SiteCollection/Style%20Library/MyImage.gif%>" />

Why won't this work? This doesn't work because the inline code is in a standard html tag and not a server control, and it doesn't get evaluated when the page is parsed, so the entire inline expression is just interpreted as a literal string. When this happens, you'll get this error:
Literal expressions like '<% $SPUrl:~SiteCollection/Style%20Library/MyImage.gif%>' are not allowed.
I know this is .Net 101, but if you aren't paying attention it's easy to overlook. So... don't forget to either use server controls, or specify a runat="server" attribute for your html tags.