Dissecting Razor, part 9: Inline Helpers

In addition to normal and static helpers, Razor supports inline helpers, (also known as templates), which allow you to create lambda expressions that return markup.

An inline helper is created by writing @<tag>Content</tag> as an expression.  This creates a lambda expression that takes a parameter called item and returns a HelperResult object containing the markup.

Inline helpers are used to create functions that take markup as parameters.  For example, you might make an IfLoggedOn helper that displays content if there is a logged-in user, but shows a login link to anonymous users.  To pass the content to the helper, you can use an inline helper:

@helper IfLoggedOn(Func<MembershipUser, HelperResult> content) {
    var currentUser = Membership.GetUser();
    if (currentUser == null) {
        <i>
            To use this content, you must 
            <a href="@Href("~/Login")">log in</a>.
        </i>
    } else {
        @content(currentUser)
    }
}

You can call this method with an inline helper like this:

@IfLoggedOn(
    @<form action="@Href("Add-Comment")" method="post">
        @Html.TextArea("Comment", "Type a comment")
        <input type="submit" name="Submit" value="Add Comment" />
    </form>
)

The @content(currentUser) call in helper method is translated by the Razor compiler into a call to the overload of the Write method that takes a HelperResult (returned from the delegate).  This overload writes the content of the HelperResult to the page without escaping it (Just like a call to a normal helper method).  Functions that take inline helpers can also get the text rendered by the helper by calling ToString() on the HelperResult.

The call to the helper method is compiled to the following C# code:

Write(IfLoggedOn(
item => new System.Web.WebPages.HelperResult(__razor_template_writer => {

    WriteLiteralTo(@__razor_template_writer, "    ");
    WriteLiteralTo(@__razor_template_writer, "<form action=\"");

    WriteTo(@__razor_template_writer, Href("Add-Comment"));

    WriteLiteralTo(@__razor_template_writer, "\" method=\"post\">\r\n        ");

    WriteTo(@__razor_template_writer, Html.TextArea("Comment", "Type a comment"));

    WriteLiteralTo(@__razor_template_writer, "\r\n   ...  </form>\r\n");

})));

The IsLoggedOn method is passed a lambda expression that takes an item parameter and returns a new HelperResult.  The HelperResult is constructed exactly like a normal helper, except that it’s in a lambda expression instead of a normal method.

Like normal helpers, then markup inside inline helpers can contain arbitrary code blocks and code nuggets.  However, inline helpers cannot be nested (since that would create conflicting parameter names)

The item parameter is implicitly typed based on the delegate type that the helper is being passed as (just like normal lambda expressions).  This allows inline helpers to accept a parameter:

@IfLoggedOn(@<text>Welcome, @item.UserName!</text>)

(The special <text> tag is used to pass markup without creating an actual HTML tag)

Next Time: Sections

37 comments:

Thank you!

Thanksa lot for this useful info

summer

Thanks for this content on the blog. Chloe

Some tips on university rankings you can check here. If you do it you will get some idea on which university to attend to

I like the helpful info you provide in your articles. I’ll bookmark your blog and check again here regularly. I am quite certain I’ll learn plenty of new stuff right here! Good luck for the next!

office.com/setup

It is amazing post, i am really impressed of your post. Its really useful. Thank you for sharing this article.
avast login
office.com/setup
Rand McNally Update

Data security is a very big issue nowadays. Viruses harm the data. Here you can know more about how to remove viruses from your computer and makes your data secure and safe.
Easy Steps To Remove Viruses
How to Remove Viruses from your computer?

Are you looking to hire top quality Custom Term Paper Help Services and cheap Legitimate Term Paper Writing Services? Rather than risking abject failure, you should consider hiring Legitimate Term Paper Help Provider.

looking for Epson Printer drivers then epson.com/connect is best place for you. Visit to get latest & updated drivers for all Epson Printer models.

looking for help with Epson Printer issues then call Epson Printer tech Support phone number. Call us to get help & support for for all Epson Printer models.


looking for help with Malwarebytes issues then call Malwarebytes tech Support phone number . Call us to get help & support for for all Malwarebytes related issues.

looking for help with Gmail Password recovery issues then call Gmail Password recovery phone number . Call us to get help & support for for all Gmail Password related issues.

Epson has been known as one of the major brands when it comes to printers. And solve all your printer queries like Epson printer offline issue, Epson printer not printing.

Know why your Epson printer not working and get all solutions for Epson printer offline issue.

Excellent information Providing by your Article, thank you for taking the time to share with us such a nice article. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. Kindly visit the LiveWebTutors website we providing the best assignment help services in Australia.

For More Info: Assignment Help Adelaide

Hire UK Essay Writers for competing Law and Other Subject Assignments from studentsassignmenthelp.com. Our writers are proficient in giving law assignment help to the students at a low cost.

Hire our Singapore Translators to complete your academic translation work.Their translation work plagiarism free,an effective,and avails in numerous pair of language.

For best thesis writing help in Auckland and Wellington visit to NZ Assignment Help. Our writers are highly professional and they are giving all the assignment help services for all local as well as international students studied in University of Auckland and University of Wellington. We have a dedicated team of 250+ assignment makers and all of them are giving 100% orignal content for your assignment help.

UAE Assignment Help is the best assignment help service provider in Sharjah and Rakcity. We are writing your content 100% written from scratch. Our highly professional team of 250+ assignment makers are giving 100% unique content for all the assignment help. We are providing our services for all the students studied in United Arab Emirates University and Dubai University.

Greetings, I’m John. I’m a writer living in London, UK. I am a fan of technology, writing. You can visit my store.
Mcafee.com/activate
Mcafee.com/activate

You need to activate your norton products?. you have to visit norton official website for download norton setup then log in your norton account with email and password. follow few steps to activate your norton setup for any help visit website.

norton.com/setup

Dragon NaturallySpeaking remains the benchmark for Windows-based speech-to-text technology.
dragon naturally speaking | dragon naturallyspeaking

McAfee Antivirus protect The basic antivirus program will do all the essential security measure www.mcafee.com/activate always protect your devices McAfee Antivirus applications which are easily available in the market and also on mcafee.com/login .McAfee antivirus offers protection to your important documents and secures your folder and files on these devices. www.mcafee.com login the most well-known antivirus for security and privacy purpose. If you wish to get McAfee antivirus on the operational system, then follow detail by detail guide by and download McAfee mcafee.com my account.
mcafee.com my account antivirus offers protection to your important documents and secures your folder and files on these devices. It's the most well-known antivirus for security and privacy purpose mcafee activate product key

McAfee service offers trusted safety to protect data and devices. So, you can shop, surf & keep all your devices safe online with the convenience of a single subscription.
www mcafee activate | mcafee login my account |
www mcafee com login
mcafee livesafe login | my mcafee account |
mcafee activation code |
mcafee.com my account

there is an expanding interest for accompanies all over the place. Thusly, this

quick increment popular has lead to bargain with quality. Kolkata Escorts

Agencies is really a name that doesn't bargain with the quality with expanding

numbers. So as to make this genuine, we have concocted a brand that gives

genuine Call Girl Services in Kolkata.
if you are intrested than you can contact: Kolkata Escorts

Microsoft Office Suite of products developed by Microsoft that includes Microsoft Word, Excel, Access, PowerPoint, and Outlook. Get some easy steps for easy downloading, installing, activating, and re-installing the Microsoft Office suite by visiting the following links.
Office.com/setup

eset internet security can be installed quickly on each device if the user follows the correct procedure. You can follow the instructions below to install the setup on your devices such as Windows PC, Mac, or mobile device. Best IT security solutions for your home and business devices. Try ESET antivirus and internet security solutions for Windows, Android, Mac or Linux OS.

Enter Norton Setup Product Key and present Norton antivirus on your PC. click Norton.com/setup Enter a New Product Key.Norton.com/setup is the great antivirus software tool that protect your system.Download Norton setup to install Norton antivirus on your computer. Activate your Norton security key for Norton setup.
Norton.com/setup

Greetings, I’m John. I’m a writer living in London, UK. I am a fan of technology, writing. You can visit my store.
Mcafee.com/activate
Norton.com/setup
Mcafee.com/activate
Mcafee.com/activate
webroot.com/safe

I recommend to write such more post like this as it will encourage others.I also recommend visiting mobile app development company

Visit McAfee Activate official site www.mcafee.com/activatein any program.

Enter your 25 digits McAfee Activation Product Key.

Sign in to your McAfee account with accreditations.

Snap Submit and Choose "Nation and language".

Once Logged in, Download your Setup in download organizer.

Run application to introduce, You're good to go to go!
for more information can visit:
mcafee.com/activate

If you suddenly face Mcafee antivirus installation error then you can instantly contact this support service team members of Mcafee and find a solution of complex issues related to Mcafee antivirus.
mcafee.com/activate

Visit McAfee official website www.mcafee.com/activate. Enter your 25 digits Mcafee activation Product Key Enter your Email and password Click Submit and Log in to your account. Once Logged in, Download your Setup in download folder. Run application to install, you’re all set to go!
mcafee.com/activate

Post a Comment