Hack: Dynamic helpers in WebPages Razor v1

It’s well known that we can create global helpers by saving them in the App_Code folder. But changes in App_Code forces app restarts and therefore its quite interesting to find out alternative ways to call functions cross files.

Here is one way – that works fine in WebPages Razor v1 (not MVC, and not WebPages Razor v2) – use the CreateInstanceFromVirtualPath method to create an instance of an existing cshtml page, and call methods within it. Like this:

    dynamic hlp = WebPageBase.CreateInstanceFromVirtualPath("~/dev/SharedHelpers.cshtml");

You can use this together with razor code aswell, as I write about in another article. But to call a dynamic function with a Func (as the razor code behaves as) you need to cast it:

@hlp.SomeHelper(new Func<string, HelperResult>(@<p>foo</p>))

Unfortunately using CreateInstanceFromVirtualPath this way is “not supported” 🙂

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s