Dissecting Razor, part 8: Static Helpers

Razor helpers can be extremely useful, but they are designed to be used only by the page that created them.

To create reusable helpers, you can create CSHTML pages in the App_Code directory.  The WebRazorHostFactory will check for pages in App_Code and create a WebCodeRazorHost instead of the normal WebPageRazorHost.

This happens before the virtual CreateHost method; in order to change this behavior, one must create an inherited RazorBuildProvider and override the CreateHost method; for more details, see the source for more details.

The WebCodeRazorHost compiles helper methods as public static methods by setting the RazorEngineHost.StaticHelpers property to true.  It also overrides PostProcessGeneratedCode to remove the Execute() method and make the Application property static. 

Static helper pages inherit the HelperPage class, a very stripped-down base class which contains the static WriteTo methods used by the helpers and some static members that expose the Model, Html, and other members from the currently executing page (using the WebPageContext.Current.Page property).

Because the generated Execute() method is removed, all content outside helpers and @functions  blocks is not seen by the compiler.  It is seen by the Razor parser, so it must contain valid Razor syntax (eg, no stray @ characters).

Here is an example:

@helper Menu(params string[][] items) {
    <ul>
        @foreach (var pair in items) {
            <li><a href="@Href(pair[1])">@pair[0]</a></li>
        }
    </ul>
}

This text and @code is not compiled.

This helper can then be called from any other code by writing PageName.Menu(...), where PageName is the filename of the CHSTML page in App_Code.  In Razor pages, it can be called like any other helper.  In normal C# code, it returns a HelperResult instance; call ToString() or WriteTo(TextWriter) to get the HTML source.

For example:  (assuming that the helper is defined in ~/App_Code/Helpers.cshtml)

@Helpers.Menu(
    new[] { "Home",    "~/"        },
    new[] { "About",   "~/About"   },
    new[] { "Contact", "~/Contact" }
)

In order to see the source, I need to insert a #error directive inside the helper block; putting it in the page itself will have no effect, since the page is not compiled.  Since the contents of the helper block are code, not markup, I don’t need to wrap it in @{ ... }.

The above helper is transformed into the following C#: (As usual, @line directives have been removed)

public class Helpers : System.Web.WebPages.HelperPage {
    public static System.Web.WebPages.HelperResult Menu(params string[][] items) {
        return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

            WriteLiteralTo(@__razor_helper_writer, "    <ul>\r\n");
            foreach (var pair in items) {
                WriteLiteralTo(@__razor_helper_writer, "            <li><a href=\"");
                WriteTo(@__razor_helper_writer, Href(pair[1]));
                WriteLiteralTo(@__razor_helper_writer, "\">");
                WriteTo(@__razor_helper_writer, pair[0]);
                WriteLiteralTo(@__razor_helper_writer, "</a></li>\r\n");
            }
            WriteLiteralTo(@__razor_helper_writer, "    </ul>\r\n");
#error
        });
    }
    public Helpers() {
    }
    protected static System.Web.HttpApplication ApplicationInstance {
        get {
            return ((System.Web.HttpApplication)(Context.ApplicationInstance));
        }
    }
}

Note that the page-level content does not show up anywhere.  The helper itself is compiled exactly like a normal helper, except that it’s static.

Although there aren’t any in this example, @functions blocks will also be emitted normally into the generated source.

Next Time: Inline Helpers

12 comments:

Thanks a lot for this tutorial


london

Great, you`ve gelped me alot in programming.

Slice within the sclera near the center of the cow's eye practicing a razor-sharp scalpel. This will leave half of the eye showing the anterior features, such as the cornea, lens, iris, and ciliary body. The other half of the cow's eye will advertise the attachment of the optic resolution to the eye.Remove and throw endlessly the vitreous humor, or the eye gel. www.makemyessay.com

About 98% of students from every corner of the world found a solution for Assignment help
and got fascinated through us. The plagiarism free writings work provided by us is highly professional, satisfying almost all the reputed colleges all over the world. Allassignmenthelp.com assist you in your assignments on any subject at any level.

It's incredibly an unfathomable and pleasing piece of data. I am fulfilled that you simply allowed this solid information to us. If it's not too much bother stay us jump forward thusly. Appreciative to you for sharing assignment help

Assignment Writing Help gives me a solution to how to score good marks and attain the attention of professor. In a competitive world, only hard work is not enough to score high but how you present your content is very important. And this I learn from Assignment Writing help. A powerful tool to score high marks in Assignment.
Online Assignment Help Services
Assignment Help Experts
Assignment Assistance
Assignment Helper
Assignment Help Online Services
Online Assignment Help
Assignment Help Online
Assignment Help

Thanks for post, Do you want a technically and quick Chemistry Assignment Help by the best experts. We help you to write chemistry assignments efficiently and help you to increase your grade in your college
Chemistry Assignment Help
Chemistry Homework Help

Personal statement writing is kind of an application where you need to write about yourself. This is kind of bio data that you present in your university for higher studies or for any job. Thus, it is an important part and you also need to follow certain rules and regulations while writing the same. Here are some of the basic rules of writing a personal statement.
My Assignment Help

I recommend you to read advices from https://justdomyhomework.com/blog/uchicago-essay-prompts if you want to apply to University of Chicago. Here you can get some essay prompts to use

Gadgets or peripheral devices like HP printer have reduced our pains to a great level by making copies or printing our important documents. Now, within few seconds, you can obtain as many prints or copies as you wish for. There are several options available in the market claiming to be the best printer in the whole world. But in reality, one that offers best alternatives in all sectors is HP industry. HP Printers are one of the well-known printers and globally accepted. But as we all know no electronic device is 100 % perfect. With passing time, you can face some error with your HP printer too. So, whenever you encounter any error, then immediately dial HP printer customer support phone number and receive step-wise resolutions from the ingenious professionals.

Thanks, great post. I really like your point of view. I am working as a support executive for Microsoft Office products. I am offering support for Microsoft Office and if you need help then contact Microsoft 365 Support +1-888-502-0222 and you can also chat us to get assistance to fix issues regarding Microsoft Office.
Office 365 Help
Office 365 Support
Microsoft Office 365 Support
Outlook Support
Outlook Support Number
Outlook Tech Support
Outlook Support Phone Number

If you want to know more about the need of organizational management and resolve your queries related to the topic you can take help from Programming Assignment Help.

Post a Comment