Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using html helpers in Razor web helper

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?

like image 658
Craig Avatar asked Oct 27 '10 11:10

Craig


People also ask

Where do we use HTML helpers?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.

What are HTML helpers in MVC ?-?

In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.

What is the difference between HTML helpers and tag helpers?

Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.

Can we use tag helpers in MVC 5?

No, but you can use the standard HTML Helpers which do a lot of the same things. And ASP.NET (non-code) MVC is absolutely not "legacy", it's still fully supported with no roadmap to end that, and so is WebForms for that matter.


2 Answers

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();
}
like image 127
GvS Avatar answered Oct 18 '22 12:10

GvS


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

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

@DisplayForm(Html)
like image 38
Darin Dimitrov Avatar answered Oct 18 '22 12:10

Darin Dimitrov