views:

635

answers:

3

I created a simple extension method for the ASP.NET MVC UrlHelper. It takes no arguments as its job is to look up the name of a stylesheet file from the configuration and return a url to the stylesheet. The extension method looks roughly like this:

public static string SiteStylesheet(this UrlHelper urlHelper)
{
    var scriptFilename = UserInterfaceConfiguration.GetSection()
                             .Mvc.SiteStylesheet;
    return urlHelper.Content(string.Format("~/Assets/Scripts/{0}",
                                           scriptFilename));
}

And I use it like this:

<link href="<%= Url.SiteStylesheet() %>" rel="Stylesheet" type="text/css" />

The method does not get executed, however, and the following is rendered:

href="../Views/Shared/%3C%25=%20Url.SiteStylesheet()%20%25%3E"

As you can see the extension method is not executed, rather the entire thing is just encoded. If I change the method signature to accept a parameter:

public static string SiteStylesheet(this UrlHelper urlHelper, string dummy)

then the extension method is executed and the output is as expected:

href="/Assets/Stylesheets/FluidCMS.css"

So my question then is this by design or is this a bug in the ASP.NET MVC Web Form view engine?

+3  A: 

When I had this problem, it was because my extension methods were in a namespace that wasn't specified in the web.config.

<add namespace="Your.Extension.Method.Namespace"/>

It goes under configuration\system.web\pages\namespaces

ajma
Thanks but the namespace that contains my extension method is in the web.config and I am still seeing the same behavior.
Thanks, fell into this one myself. Also hadn't noticed that there are 2 web.configs
TreeUK
A: 

I think you found a bug!

I tried it and found this only happens in the head section of a Master Page and only in the <link> tags (<script> tags render fine).

The problem obviously is the text inside de href attribute is not correctly interpreted as a code nugget.

This goes beyond ASP.NET MVC. I tried it in a Master Page in a classic Web Form ASP.NET site and the problem persists. It seems to be a bug in the Web Form rendering engine or something like that.

Gerardo Contijoch
Thanks for the confirmation and the further details. At this point, the workaround, though hacky, is simple enough and not intrusive. Thanks again.
+2  A: 

This issue has come up a number of times. The root of the issue is that the <head> tag has runat="server", which causes the parser to treat tags as server tags.

The simplest workaround is to just remove runat="server" from the head tag. What you lose is the logic that makes the link URL's relative to the current page, but since you're using your helper anyway, you have no need for this.

David Ebbo