Click here to Skip to main content
Click here to Skip to main content

ASP.NET Razor @Helpers Passing in Another @Helper Trick!

, 30 Apr 2013
Rate this:
Please Sign up or sign in to vote.
Trick of using @Helpers in @Helpers in ASP.NET Razor

Introduction

This tip quickly demonstrates how to show raw HTML markup inside a razor's @Helper method, using another @Helper object on some .cshtml razor website page. This solution solves the issue of trying to put large markup into a single string variable, allowing instead to quickly pass RAW markup. Using this solution, you can create 'Template' like HTML markup solutions, which can be reused within your website.

Using the Code

Recently, I wanted to create a webpage using the new ASP.NET with Razor syntax. My idea was that I somehow wanted to create a standard format, kind of like a ASP "Masters" page, but more modular so it could be used in smaller byte sizes on any webpage. In other words, the idea is to drop some reusable code, which I will call a 'Template', onto the webpage and then add further markup within some 'Content' section.

With this in mind, I discovered the 'Section' semantics in HTML5, which allows you to section out a part of the HTML body as a section of importance. However, this still wasn't good enough for my solution. With some further research, I discovered another '@Section' razor keyword which was closer to the solution.

The '@Section' razor keyword allows you to set defined sections within the razors 'Layout' pages. These defined sections can be then set with predefined markup, like containers using division '<div>' and then define headers '<h>' and paragraphs '<p>'. Then a content .cshtml razor page can then drop this '@section' page into the HTML page, allowing the page to be controlled in some fashion. This excited me, because the new razor '@section' syntax allows you to set a requirement property, forcing this section to be used; kind of like a policy. But, this still wasn't the solution I was looking for. Why? Because even though this allowed me to section out parts of the entire webpage, I still needed a way to drop smaller 'Template' like "HTML" code within each of these sections.

This then brought me to another one of razors keyword; '@Helpers'. "What is this?", I asked. Peeking around the Visual Studio's Express environment, I noticed I could add specific 'Helpers'  .cshtml type pages, which contain this syntax. Well, it turns out the helpers are like C# methods, but with the extra benefit of adding HTML Markup right into the code body!

An example of this syntax is given below:

@helper HeaderContainer(stri ng headerText, object contentText = null, string className = "BensStyle1")
{       
    var headerTextToSet = string.IsNullOrEmpty(headerText) ? "Set Your Header" : headerText;    
    
    <div class="@className" >
        <h2 id="Header">@headerTextToSet</h2>
        <div>
            <p id="Content">@Html.Raw(@contentText)</p>            
        </div>
    </div>
} 

Now, using this new @Helpers syntax, I could now drop these right into any content page, thereby immediately giving me the HTML markup reuse.

An example of using this @Helper:

<section>  

       @Helper1.HeaderContainer("Hello", "This is cool!", "erer")
       @Helper1.HeaderContainer("Third Time", "Look at this stuff!")         

</section>

But this still wasn't enough!! I now needed a way to pass RAW HTML markup into the method, thereby allowing me to fill any content section with some RAW markup. I did a search and found that razor has a HTML helper called '@html.Raw()', allowing you to pass strings and 'Object' as the parameter type. I first tried the strings, which worked perfectly. Unfortunately, the strings are limited when you have large areas of HTML markup you want to use. With some more determination, I finally discovered the solution!! The solution is simple... add another '@Helper' method, which ONLY contains the HTML markup you want to show in the content section of the original @Helper method. Since the '@HTML.Raw()' method call accepts an 'Object' as one of the parameters, I figured this should allow the razor engine to consume this object and displayed it correctly. Sure enough, it did.  

Below is the final solution:

Create the webpages content @Helper;
@helper TestThisStuffContent() {
    
     <div style="background-color:red;">
        <h1 style="color:aliceblue;">Eat This Stuff.</h1>
        <p>This is the best stuff you will every eat in your life!  Take some now, and eat at home.</p>
    </div>
}

And then pass this object into the original @Helper method as an object param;
@Helper1.HeaderContainer("Play", @TestThisStuffContent())

Points of Interest

I discovered while researching this topic that the razors view is different from the .aspx view. I originally tried to use a "Web Server Control" as the template in the razors view, but quickly discovered this solution did not work! This then led me into discovering the @Helpers methods, which opened the door to the HTML.Raw() object call, and finally seeing the 'Object' overload for this helper. If it wasn't for the 'Object' overload, my idea to pass the additional @Helper markup call would have never worked!

History

  • 30th April, 2013: Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

BenScharbach
Software Developer (Senior) Image-Nexus, LLC
United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 30 Apr 2013
Article Copyright 2013 by BenScharbach
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid