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) {
        @foreach (var pair in items) {
            <li><a href="@Href(pair[1])">@pair[0]</a></li>

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)

    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");
    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


«Oldest   ‹Older   1401 – 1455 of 1455   Newer›   Newest»

Hire a qualified Civil Engineering Assignment Help service to get assignments which score higher grades. Each of our experts is highly qualified in their assignment writing services .

We provide Assignment Help Australia covering all the subjects. Our assistance is a great support to student in excelling good grades . . Avail best Australian assignment help services from Online Assignment Expert.

Best and nice article. We provide service in write my assignment which is required by college student. We have best assignment writing team with us.

Anamalai Tiger Reserve is a fantastic destination to come with your family if you want to see mangrove forests, teak plantations, bamboo groves, and stunning views. The Panther, Tiger, Elephant, Deer, Wild Dogs, Civets, Porcupines, Jackals, Black-headed Oriole, Red Treepie, Racket-tailed Drongo, and many other creatures and birds you've never seen or heard of are among them. If you're looking for a unique combination of magnificent vegetation, fascinating wildlife, and adventure, Anamalai Tiger Reserve provides something for everyone. The Anamalai Tiger Reserve offers a variety of activities, including trekking, elephant rides, photography, jungle safaris, and bird viewing.
Anamalai Tiger Reserve

Our professional gallery Manhattan Picture Hanging services are perfectly curated for all your significant exhibitions and events. Since each picture has a story to tell, we offer a professional approach for your gallery or exhibition picture hanging demands.

Programming Assignment Help
Elevate your grade with our programming assignment help services at our reliable website. The experts of British Dissertation Help can deal with any complex topic related to Java, C++, python, visual basic, PHP, Pascal, Oracle and much more. Our company has established a stellar reputation due to unlimited free edits, timely delivery, and plagiarism-free solutions.

I feel happy concerning and learning additional concerning this blog. Keep sharing your data frequently for my future reference. This content creates new hope and inspiration among me. Thanks for sharing a blog like this. The knowledge you have provided is better than another blog. Visit here:Rcedutalent

Change Your Flight With Spirit Airlines Change Flight . You can change your flight with Spirit Airlines on the same day, can check online for the whole procedure and passengers can call us (+1-877-805-09980) to change your flight on call.

MetaMask is a cryptocurrency wallet that enables users to access the Web 3 ecosystem of decentralized applications (dapps).Thanks for this information
MetaMask Log In
MetaMask Log In
MetaMask Wallet
MetaMask Extension

You've recently relocated into your lovely new house or workplace. Perhaps you've just completed refurbishing your previous one. And you want everything on your property to be absolutely flawless. NYC Art Installation can assist you with the best Picture Installation NYC services.

Hashtags are essential for making your content more discoverable. It's like putting random items into a box. How to get more views on Instagram. So, whenever you need it, simply go to the 'box' and look for it. It's the most basic illustration of hashtags. You should also be aware of the hashtag usage rules. You can't do it at random, either. It's best if you utilise no more than 30 hashtags each reel. Choose hashtags that are relevant to the type of content you're posting. It will allow the Instagram algorithm to recognise the topic of your reel and discover the best way to reach the right audience.

Lots of good advice here, but i want to plead with anybody planning to approach a blogger to read the blog. Check This FilmyZIlla

Very useful information! None of my language teachers took the time to thoroughly describe every aspect of writing my paper. The comments you can give at the end of each article are a form of evaluation. As a result, I had a constant yearning for it! This essay can assist you in improving your ability to write my paper. Thank you very much!

I am Amara William. I am always ready to learn new things and resolve problems regarding.
I am helping you to resolve your quick book error,I have been an independent expert for the last 5 year to solve all errors of QuickBooks , working dedicatedly with the reliable QuickBooks support provider for resolving QuickBooks errors efficiently. contact me
Fix QuickBooks has stopped working or not responding error

Get a wide selection of Canada's top electric bikes. Order a low-cost electric bicycle from VoltBike and discover the thrill of riding. Our electric tricycles are so simple to ride that they'll make you smile. A beautiful and comfy three-wheeler that makes cycling fun for everyone.

Can I Use Cash App Borrow To Take Money From Cash App Account?
As a Cash App account holder, you can make proper utilization of Cash App Borrow feature to take money up to $20 to $200 without any kind of hassle. In case of any difficulties, you will be able to make use of expert’s assistance and support so that you can understand its terms and conditions.

Construction Assignment Help - Building and construction assignment help is offered by the genius writers of All Assignment writing services where they draft an A-grade work

How to find the Cash app bank name?
Most people are not aware of the Cash App Bank Name; hence they keep on looking for the same every time. They can initiate with launching the cash app on their device and click on the balance tab. later they can choose to take the help of the support service team as there might be a possibility for the appearance of hurdles. However after they get the routing number, then they can quickly seek out the cash app bank name just below that.

Замечательный портал знакомств вhttps://sitedating.ru/ интернете для поиска партнера и отношений. Гигантская база анкет соискателей знакомств со всего мира. Бесплатная регистрация не требующая ввода номера телефона. Практичный поиск по анкетам знакомств. Регистрируйтесь и найдите свою большую любовь прямо сегодня

It is a best assignment services in UK . They complete our work in less time with professional writers and give good services.

Nice blog! Great work. Keep it up.
Do you want to sell your phone in good price? Click here : sell mobile phone

The most reliable HP printer support services
We provide exclusive and customised support for all types and the entire range of HP printers. Our team of experts are well versed with all the technical and mechanical needs of the HP printers Supports. In case you are planning any HP printer purchase then we can help you solve all the basic and technical support for the same.

There are instances of heart problems, such as hypertension, are treated with Fildena Super Active
tablet by your doctor, but each diagnosis is made under the supervision of a your consultant doctor or pharmacist.
Vidalista CT 20
Vidalista Professional

Can I Use Cash App Business Account If Already Have A Personal Cash App Account?
Of course, you can have a new Cash App Business Account even though you already have a Cash App account for personal usages. For that, you have to arrange a new email account along with a new phone number. Apart from that, you will also need to use a unique bank account that must not be linked with your previous Cash App account. In case of any hassle regarding the same, you should take necessary support from an adept Cash App team.

How To Borrow Money From Cash App If You Are Not Eligible?
If you are one of those Cash App account holders who are going to take a loan on Cash App without confronting any kind of loopholes and hurdles, you will have to get in touch with the Cash App geeks who will help you out understand How To Borrow Money From Cash App
in a trouble-free manner. To find a quick and reliable source of information, you should navigate through the official help section without making any delay.

Great and very informative learnt alot from your article..


Very good blog post, it is very well written and your points are well-expressed. Thanks for sharing cross rivers state college of health tech admission list, visit Best Rated Educational Update Portal in the World; Examination and Academic Guide, High Paying Jobs & Scholarship  Website.

Don’t worry! You should directly refer to the official Facebook help center without making any kind of delay if you would like to know about How Do I Unfriend or Remove a Friend on Facebook To do so, you should directly go to the profile of the person you would like to unfriend from your Facebook.Here, you will have to click on the unfriend option to unfriend him/ her from your Facebook friend list.

Do you want to unblock a blocked Facebook friend without having to confront even a single issue? For that, you will first go to the official help center where you will be able to determine the right instructions and guidelines to understand How To Unblock Your Friends On Facebook In case of any issues regarding the same, you can try approaching any proficient geeks who will assist you out.

Great Article. I really like your blog. Keep sharing more.Its really the best article!
ShapeShift | Swyftx Login

Thanks for the post keep sharing.Its really the best article!Unique content! Coinbase Wallet | Atomic Wallet

Pancake Swap allows users to earn an additional yield by staking supported liquidity provider (LP) tokens in one of its numerous yield farms. By participating in a yield farm, users earn a CAKE yield on their LP tokens. This is on top of the yields generated through transaction fees.

Hubstaff is conceptually designed time tracking software that helps and allows its users to monitor employee’s activities during work hours. It also allows employees to track time through its desktop app where employees can choose to record their time. This app adds the time logged in by various employees and tells the amount of time needed to complete the entire project. This time tracking software also creates an invoice by using this information and allows to bill your clients, based on the hours spent. After successful integration of Hubstaff with QuickBooks, it becomes easier to export reports and gets time tracking timesheets, and more. When Hubstaff is running, it becomes easier to monitor which websites and applications and other screen activities, your team is viewing on their desktop. It also gathers all types of data and creates individual reports for all your employees. It will help your team members to track down the amount of time they have spent on each task or project. https://quicklybookonline.com/quickbooks-hubstaff-integration/

quickbooks vend integration By integrating these two apps, users can accelerate their accounting workflows so that you can less time on accounting and more time on your business. The integration process automatically syncs sales, cost of goods (COGS) and On Account sales and also keeps tracks of purchase orders by posting them directly as accounts payable invoices. LINK:-

anks for sharing this informative information with us. This is a fantastic website, thanks for sharing.
Pro.coinbase.com | Coinbase wallet

With a simple step by step process, you can easily do the Bitdefender setup activation. A very competent antivirus software, Bitdefender offers complete security against online threats. You can protect one or many devices with a single IBitdefender activation key license. But of course, it depends on your purchased subscription. After you have completed the Bitdefender setup activation, you can download the product via your central Bitdefender account and install it on your computer to enjoy the protection. https://threatprotections.com/bitdenfender.php


quickbooks hubspot integration
HubSpot is a resourceful CRM platform which is user-friendly and intuitive in nature. It’s one of the highly rated CRM software for small and mid-size businesses who want to consolidate and enhance their sales, marketing and customer service tools.
LINK:- https://quicklybookonline.com/quickbooks-hubspot-integration/
LINK: LINK:- quickbooks hubspot integration

MetaMask Sign in- Buy, store, send and swap tokens
Metamask Sign in

If your company wants best book scanning service, Acadecraft is the best option. The company has professionals who are flawless in their jobs.
It offers accurate, authentic, and cost-effective services. For free quotes, reach out at info@acadecraft.com.

Thanks for sharing this amazing blog . I appreciate for this performance . homework help singapore

Thanks for sharing this informative information with us. This is a fantastic website, thanks for sharing.

cuevana3 | Pelisplus

Why do we need Canon mg7520 troubleshooting?
We require Canon mg7520 troubleshooting for reasons like unresponsive printer, Printer won't print, Bad print quality, uncertainty about printer security, and my printer won't scan, lots of paper jams, slow printing, and, expensive printing.

many years of experience in washing machine Service industry. Website : Book Washing machine Repair Service in Nagpur

Great Blog
Need help with your essay assignments in Singapore? MY Assignment Help Singapore is here to provide you with expert "essay help singapore" services. We offer customized solutions to meet your unique academic needs and requirements.

Thanks for sharing the information keep updating, looking forward to more post.
find a bankruptcy attorney near me

This comment has been removed by the author.

nice blog
Need help with your assignments? Our assignment help service provides access to professional PhD writers who are experienced in a wide range of subjects. From research papers to essays, we've got you covered. Contact us now for personalized and efficient assistance.

nice blog keep sharing
Are you ready to become a digital marketing expert and take your career to the next level? Our digital marketing course in Jaipur can help you achieve that goal. Our course is designed to provide you with the in-depth knowledge and practical skills you need to excel in digital marketing. From creating effective digital marketing strategies to implementing data-driven campaigns, we cover all the essential topics. Enroll today and become a digital marketing expert with our comprehensive course!

A big thank you for your blog really looking forward to read more ,fantastic .
Henrico VA Menor Posesión Alcohol

«Oldest ‹Older   1401 – 1455 of 1455   Newer› Newest»

Post a Comment