14

I am trying to create a Razor web helper something like this :

@helper DisplayForm() {    
    @Html.EditorForModel();    
}

But this gives the error "CS0103: The name 'Html' does not exist in the current context".

Is there any way to reference html helpers within web helpers?

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Craig
  • 36,306
  • 34
  • 114
  • 197

3 Answers3

23

You can cast the static Page property from the context to the correct type:

@helper MyHelper() {
    var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;

    Html.RenderPartial("WhatEver");
    @Html.EditorForModel();
}
GvS
  • 52,015
  • 16
  • 101
  • 139
  • 1
    Thanks, worked for me. Now can anyone answer the question of why the `System.Web.WebPages.Html.HtmlHelper` version exists at all? – Kirk Woll Jan 03 '11 at 20:59
  • 6
    You can always add this at the top of your file: `@functions { public static System.Web.Mvc.HtmlHelper Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html; }` Given that you can use `@Html` as everywhere else. – pinus.acer Jan 09 '13 at 12:28
4

Declarative helpers in Razor are static methods. You could pass the Html helper as argument:

@helper DisplayForm(HtmlHelper html) {
    @html.EditorForModel(); 
}

@DisplayForm(Html)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • When I try this I get the error "CS1061: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'EditorForModel' and no extension method 'EditorForModel' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)" – Craig Oct 27 '10 at 20:49
  • That's because your view needs to be strongly typed: `@model MyNs.Models.FooViewModel`. – Darin Dimitrov Oct 28 '10 at 20:34
1

Razor inline WebHelper is generate static method.

So can not access instance member.

@helper DisplayForm(HtmlHelper html){
    @html.DisplayForModel()
}

How about this?

takepara
  • 10,413
  • 3
  • 34
  • 31