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?

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, worked for me. Now can anyone answer the question of why the System.Web.WebPages.Html.HtmlHelper version exists at all?
You can always add this at the top of your file: @functions { public static System.Web.Mvc.HtmlHelper<object> Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html; } Given that you can use @Html as everywhere else.
4

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

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

@DisplayForm(Html)

2 Comments

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?)"
That's because your view needs to be strongly typed: @model MyNs.Models.FooViewModel.
1

Razor inline WebHelper is generate static method.

So can not access instance member.

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

How about this?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.