4

I've got a ASP.NET MVC 3 Razor Web Application.

I've got a WebViewPage extension:

public static bool Blah(this WebViewPage webViewPage)
{
   return blah && blah;
}

And i want to access this from my HtmlHelper extension:

public static MvcHtmlString BlahHelper(this HtmlHelper htmlHelper, string linkText, string actionName)
{
   // how can i get access to the WebViewPage extension method here?
}

I can of course duplicate the functionality of the WebViewPage extension if i had to, but just wondering if it's possible to access it from the HTML helper.

RPM1984
  • 72,246
  • 58
  • 225
  • 350

4 Answers4

10
// Warning: this cast will crash
// if you are not using the Razor view engine
var wvp = (WebViewPage)htmlHelper.ViewDataContainer;
var result = wvp.Blah();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I had the same problem and the accepted answer led me to the solution (+1). Maybe this hint helps somebody else too. Additionally I had to use the generic version of WebViewPage inside a strongly type view. Otherwise I got a type cast exception.

public static MvcHtmlString ToBodyEnd<TModel>(this HtmlHelper<TModel> htmlHelper, ...) {
       var vp = (DerivedWebViewPage<TModel>)htmlHelper.ViewDataContainer;
    //... more code ...
    }
Andreas
  • 2,252
  • 1
  • 19
  • 29
0

You should change that method to extend HttpContextBase, which you can access from both HtmlHelper and WebViewPage.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • the question wasn't really about the functionality of the extension, but how to achieve what i'm asking in a general sense. I've edited the question to reflect that – RPM1984 Dec 22 '11 at 02:08
  • I don't think that's possible; explore `htmlHelper` in the Locals window and see if you can find it. – SLaks Dec 22 '11 at 02:49
0

I would try:

((WebViewPage)htmlHelper.ViewContext.View). Blah()
ryudice
  • 36,476
  • 32
  • 115
  • 163
  • Nice try. It appears that `View` is actually the view engine, not the view page. And i'm using a custom view engine (Razor CSHTML generator), so the type is `PrecompiledRazorViewEngine`. – RPM1984 Dec 22 '11 at 02:26