I think I know what's causing the issue...
The definition of the Html property getter is:
public static HtmlHelper Html {
get {
WebPage currentWebPage = CurrentPage as WebPage;
if (currentWebPage == null) {
return null;
}
return currentWebPage.Html;
}
}
Setting a breakpoint in my helper method shows that CurrentPage is not in fact an instance of WebPage, hence the null value.
Here is the type hierarchy of CurrentPage (my class names doctored slightly):
ASP._Page_Views_mycontroller_View_cshtml
My.Site.MyWebViewPage`1
System.Web.Mvc.WebViewPage`1
System.Web.Mvc.WebViewPage
System.Web.WebPages.WebPageBase
System.Web.WebPages.WebPageRenderingBase
System.Web.WebPages.WebPageExecutingBase
System.Object
Note that the base class of my view has been specified in Web.config:
<system.web.webPages.razor>
<pages pageBaseType="My.Site.MyWebViewPage">
...
Which is defined both in generic and non-generic form:
public abstract class MyWebViewPage : WebViewPage { ... }
public abstract class MyWebViewPage<TModel> : WebViewPage<TModel> { ... }
So, if this problem does not occur for others, perhaps they're not using a custom pageBaseType.
Note too that I've placed the @helper declaration in App_Code\Helpers.cshtml in the hope of making it globally accessible.
Am I doing something wrong, or is this a bug?
EDIT Thanks Darin for pointing out this as a known issue. Still, why isn't the Html property redefined as:
public static HtmlHelper Html {
get {
WebPage currentWebPage = CurrentPage as WebPage;
if (currentWebPage != null) {
return currentWebPage.Html;
}
WebViewPage currentWebViewPage = CurrentPage as WebViewPage;
if (currentWebViewPage != null) {
return currentWebViewPage.Html;
}
return null;
}
}