Dissecting Razor, part 7: Helpers

We’ll continue our trek into Razor’s class-level features with helpers.

Helpers are one of Razor’s unique features.  They encapsulate blocks of HTML and server-side logic into reusable page-level methods. 

You can define a helper by writing @helper MethodName(parameters) { ... }.  Inside the code block, you can put any markup or server-side code.  The contents of a helper are parsed as a code block (like the contents of a loop or if block), so any non-HTML-like markup must be surrounded by <text> tags or prefixed by the @: escape.

Here is a simple example:

<!DOCTYPE html>
        @helper NumberRow(int num) {
            var square = num * num;
                <td>@(num % 2 == 0 ? "Even" : "Odd")</td>
                @for (int i = 0; i < 10; i++) {

Note that code statements (such as the square declaration) can go directly inside the helper body without being wrapped in code blocks – the direct contents of the helper is a code block, not markup.  Like any other code block, HTML-like markup is automatically treated as markup instead of code.

Like @functions blocks, helper methods can go anywhere in the source file; the physical location of the block is ignored.

Here is the generated source for the above example: (with blank lines and #line directives stripped for clarity)

public class _Page_Razor_Helpers_cshtml : System.Web.WebPages.WebPage {

    public System.Web.WebPages.HelperResult NumberRow(int num) {
        return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

            var square = num * num;

            WriteLiteralTo(@__razor_helper_writer, "            <tr>\r\n                <td>");
            WriteTo(@__razor_helper_writer, num);

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n                <td>");
            WriteTo(@__razor_helper_writer, square);

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n                <td>");
            WriteTo(@__razor_helper_writer, num % 2 == 0 ? "Even" : "Odd");

            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n            </tr>\r\n");

    public _Page_Razor_Helpers_cshtml() {
    protected ASP.global_asax ApplicationInstance {
        get {
            return ((ASP.global_asax)(Context.ApplicationInstance));
    public override void Execute() {
        WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n    <body>\r\n        ");
        WriteLiteral("\r\n        <table>\r\n            <thead>\r\n                <tr>\r\n                   " +
        " <th>Number</th>\r\n                    <th>Square</th>\r\n                    <th>E" +
        "veness</th>\r\n                </tr>\r\n            </thead>\r\n            <tbody>\r\n");

        for (int i = 0; i < 10; i++) {

        WriteLiteral("            </tbody>\r\n        </table>\r\n    </body>\r\n</html>\r\n");


Helpers are compiled as class-level methods that take a parameter set and return a System.Web.WebPages.HelperResult.  (This class name is configured by the RazorHostFactory)

Notice the the contents of the helper method are inside a lambda expression that takes a parameter named __razor_helper_writer.  This construction allows the helper to write directly to the HTTP response stream instead of assembling a giant string and then writing the string all at once.

The HelperResult constructor takes an Action<TextWriter> which contains the contents of the helper block.  The class implements IHtmlString and calls the action from the constructor to generate HTML.  However, under normal circumstances, this IHtmlString implementation is never called.

Calls to helper methods (@NumberRow(i)) are passed to the Write(HelperResult) overload.  This overload calls HelperResult.WriteTo(writer), which passes the page’s TextWriter directly to the helper’s lambda expression.  Thus, the lambda expression can write directly to the page’s output stream, without passing the output as a parameter to the helper method.

Looking inside the helper, we see that all content is passed to WriteTo and WriteLiteralTo methods, as opposed to the Write and WriteLiteral methods used by the rest of the page.

Helper methods cannot call the normal Write* methods since they aren’t necessarily writing to the current output (even though they usually do).  Therefore, they call these Write*To methods, which accept the TextWriter as a parameter.  These static methods are inherited from the WebPageExecutingBase class; their names are also configured by the RazorHostFactory.  The @ in the parameter is a little-used C# syntactictal feature that allows keywords to be used as identifiers; it has nothing to do with Razor’s use of the @ character.

Since helpers are compiled as normal methods, they can do almost anything that a normal method can.  However, because their contents are compiled inside a lambda expression, they have some limitations.  For example, helpers cannot use ref or out parameters, since they cannot be used inside lambda expressions.  Helpers can take params arrays or optional parameters.

Also, Razor’s C# code parser doesn’t support generic helper methods, although there is no reason that they couldn’t be supported in a later release.

The VB.Net code parser also doesn’t explicitly support generic helpers.  However, because VB.Net generics use parentheses, a VB.Net helper can declare a generic type parameter instead of a normal parameter list.

For example:

<!DOCTYPE html>

        @Helper PrintType(Of T)
        End Helper
        @PrintType(Of Dictionary(Of Integer, List(Of String)))()


This trick is not very useful.

Next Time: Static Helpers


Interesting to read about that


This article should read more people.
phone girls in London

Do you want to learn more about writing a proposal? On https://nerdymates.com/blog/how-to-write-a-proposal you can read more about it

We will discuss HTML which is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript. It is also very useful for developers. Dissertation proposal writing services.

I loved the article, keep updating interesting articles. I will be a regular reader I am offering assignment help to students over the globe at a low price.
doodle face online

I read this article and it appears to be very interesting seriously. It’s a kind of new post I’ve ever met. I want to know more interesting features for the future from you!!
Thanks for sharing this post!!
How to tell if your girlfriend has had bigger

Selection of good accounting tool is necessary as there is two tool quicken and quickbooks and both are accounting website but the difference is that and quicken is cheap small accounting tool and quickbooks is big all in one accounting tool with core accounting and payroll while comparing the quicken home and business vs quickbooks

The very next time I read a blog, I hope that it won’t fail me as much as this particular one. I mean, Yes, it was my choice to read through, however I genuinely believed you would have something helpful to say. help with assignment writing uk All I hear is a bunch of complaining about something that you could fix if you weren’t too busy searching for attention.

Thank you so much for your information. I really appreciate you thinking of me, and you couldn't have chosen a more perfect present for me. Again, thanks very much. for More Information Click Here:- Change Verizon Email Password

Ah, why am I so bad at understanding technical stuff? I think I need to share it with my friend who will explain it to me. He’s out now, and till he returns, I think I better start looking for a website that provides Assignment Help Usa- based. I am sure I will find one before he returns and once he does, we will talk about this post.

I want to say that is one of the top notch posts that i've perused in all my existence. the whole thing right here is certainly remarkable. I couldn't essay writing company have requested a highly improved put up than this. . i am capable of bookmark your internet web site and advocate to all my pals

I once tried to have a razor view of my project but couldn’t manage it so I took my friend’s help instead. I was never a technology person rather I am a writer who just knows to open a laptop and provide Dissertation Presentation Help to the students who need guidance and assistance in their assigned projects.

Thanks for such a unique blog; I would advise you to establish a suitable plan for your blog and begin professional blogging as a vocation; one day you will be wise enough to travel agents in delhi for international flights to earn some money; wishing you the best of luck, my friend. Thank you so much for your kind words of encouragement and love.

This is wonderful blog post. It really makes me happy while reading it and I am satisfied with the arrangement of your post and there some other blogs also like cheapest cloud storage providers and
Buy Wondershare. You are really a talented person I have read after long time. I have bookmarked your site.

One of Razor's distinguishing qualities is the presence of helpers. They're reusable page-level methods that it is truly amazing how Do My Assignment For Me uk works in a highly systematic order to provide the premium quality paper writing service to students.

So far really good. Goods haven’t been delivered yet, but the ordering process, choice of excellent products and seemingly the price/value seems really excellent, roseland furniture discount code.

The programming language Razor makes it easy to insert server code into web pages. The ASP.NET framework, a portion of the Microsoft.NET Framework created primarily for building online applications, serves as the foundation for Razor syntax. The Razor syntax provides you all the power of ASP.NET while employing a more straightforward syntax that is simpler for beginners to understand and more efficient for experts. The HTML pages that contain both HTML content and Razor code are known as Razor web pages. Prior to sending the HTML page to the browser after reading the document, the server executes the Razor code. Tasks that cannot be completed in a browser can be carried out by code that is run on the server. Get True Surf now for your pc.


Incorporating server code into web pages is simple with the programming language Razor. Razor syntax is built on top of the ASP.NET framework, a component of the Microsoft.NET Framework designed particularly for developing internet applications. Take my online class.

Your feature helped me in my project. I faced an issue in my project but the code you have provided it helped me a lot. Please share more. Now it's time to avail Inbound Call Center for more information.

This article is in HTML code language. The writer provides helped us with the logical method. This information is very effective. Now it's time to avail shutters in birmingham for more information

Thanks for sharing this code i found this lot of websites but i could't find Now i found it. Thanks. Now its time to avail grocery store near mefor more details.

really thankful its very helpful code for HTML user i found this lot of websites but, I couldn't find Now i found it. Now its time to avail solar panels for homefor more details.

The the next time Someone said a weblog, Hopefully that it doesnt disappoint me approximately this place. After all, Yes, it was my substitute for read, ember morely coat but I just thought youd have something intriguing to say. All I hear is a handful of whining about something you could fix in case you werent too busy interested in attention.

This article helped me a lot in my HTML assignment. You explained it very well in a comprehensive way that it is so easy to understand. Thanks for sharing this with us. Now it's time to avail airport chauffeur service for more information.

This is amazing idea for beginners who want to learn coding. It is also helpful for making HTML notes for users. Your explanation method is very understandable. Thanks for sharing. It's time to know about y2 mate for more details.

The hyper text markup language are mostly used for creating website. This blog is very informative and helpful for students who want to learn coding. Thanks for sharing this with us. Now it's time to avail this Ac services in Al Qusais visit us to more services.

Thanks for sharing the code with us many students would be helped with your nice gesture. While talking about helping students many students want help with online class and they have been searching for it online.

With the programming language Razor, incorporating server code into web pages is simple. Razor syntax is built on top of the ASP.NET framework, a Microsoft.NET Framework component designed specifically for developing internet applications. Pay someone to do my online class

If you're looking for an exciting way to learn, consider taking an do my online course. Helers are class-level methods that return a System.Web.WebPages.HelperResult, so they're perfect for learning new things quickly and easily. Plus, you can take courses from anywhere in the world, at any time of day or night. So why not give it a try?

Thank you for sharing this post! you done great effort, it is very useful for me
Washington Condado DUI VA

Thanks for sharing your insights on razor helpers! It's fascinating to learn about the various tools and techniques used in shaving. However, it's also important to be mindful of any potential skin irritations or injuries. If you're experiencing any issues, it's always best to doctor to consult to ensure that your skin is healthy and well-cared for. Here's to a smooth and safe shaving experience!

I love read a blog.. It is creativity and great blog.. Thanks for this lovely blog..

Abogado de Lesiones Personales Virginia

I think you are searching Reckless Driving Lawyer Hanover Virginia, Good just click above button.

Introducing Razor, the ultimate test taker for hire. Are you tired of the stress and pressure that come with exams and tests? Look no further, as Razor is here to revolutionize the way you approach academic challenges

I read that Post and got it fine and informative. Please share more like that.
wire fraud lawyer

Awesome article! I want people to know just how good this information is in your article. It’s interesting, compelling content. Your views are much like my own concerning this subject. I also wanna talk about animal sanctuary volunteer

If you set out to make me think today; mission accomplished! I really like your writing style and how you express your ideas. Thank you. Here I also wanna talk about private football lessons

Abogado Tránsito Sussex VASeeking a Traffic Attorney in Sussex, VA? Our experienced Abogado de Tránsito (Traffic Lawyer) in Sussex, VA, is dedicated to protecting your rights and providing expert guidance in traffic-related legal matters. Contact us today for skilled legal representation.

Post a Comment