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>
<html>
    <body>
        @helper NumberRow(int num) {
            var square = num * num;
            <tr>
                <td>@num</td>
                <td>@square</td>
                <td>@(num % 2 == 0 ? "Even" : "Odd")</td>
            </tr>
        }
        <table>
            <thead>
                <tr>
                    <th>Number</th>
                    <th>Square</th>
                    <th>Eveness</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < 10; i++) {
                    @NumberRow(i)
                }
            </tbody>
        </table>
    </body>
</html>

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++) {
            Write(NumberRow(i));
        }

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

    }
}

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>
<html>

    <body>
        @Helper PrintType(Of T)
            @GetType(T)
        End Helper
        @PrintType(Of Dictionary(Of Integer, List(Of String)))()
    </body>

</html>

This trick is not very useful.

Next Time: Static Helpers

31 comments:

Interesting to read about that


jaqueline

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.

mr jatt Mp3 New Punjabi Song,Single Tracks Latest song download also Listen Latest Music Albums Online in High Quality at Mrpendus.in
mr jatt

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

It is important to seek english language essay writing services and english language coursework writing services since students find help when they visit English Language Writing Services.

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

Thanks for such wonderful blog that looks pretty different, I would suggest you please make a proper plan for your blog and start professional blogging as a career, One day you would be smart enough to earn some money, write my assignment for me wishing you a best of luck my friend, Thanks a lot for your nice support and love.

I will always let you and your words become part of my day because you never know how much you make my day happier and more complete. There are even times when I feel so down but I will feel better right after checking your blogs. help with dissertation You have made me feel so good about myself all the time and please know that I do appreciate everything that you have

Thanks for such wonderful blog that looks pretty different, I would suggest you please make a proper plan for your blog and start professional blogging as a career, One day you would be smart enough to assignment writing help earn some money, wishing you a best of luck my friend, Thanks a lot for your nice support and love.

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.

Read More...

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.

Post a Comment