Creating Helpers for ASP.NET Web Pages with WebMatrix

If you are unfamiliar with helpers and haven’t read my blog post on “Getting Started with ASP.NET Web Helpers for WebMatrix”, you should start reading there.  Otherwise, we’ll move on to create helpers for use with the Razor View Engine and WebMatrix.  In a later post I’ll describe how to create helpers using Visual Studio 2010 for use in WebMatrix.

There’s four steps to creating helpers for Razor views.

1. Create the helper file.

The helper file belongs in the \App_Code folder located under your site’s root.  If there is no \App_Code folder in the project, go ahead and create one.  You can name it whatever you’d like, but note that the name of the helper file without the extension will be used in the calling syntax and the extension must be .cshtml. In MVC with VS 2010, helper are stored as .cs or .dll files instead.

cshtml_2

 

2. Add the @helper directive to the top of the helper file.

Here’s what the signature for a helper looks like:

@helper HelperName([DataType arg], [DataType arg]…) { // helper code }

 

You can store multiple helpers in a single .cshtml file, as well as functions which we’ll look at in the next section of this post.  Each helper works syntactically as if it’s a static method when called (more on that below).

3. Add code, markup and text.

Start adding elements that you want to render and don’t forget that Razor code is case sensitive.  In this example, a helper named  RenderDiscountedPrice that accepts a decimal input and renders out a message displaying the featured product’s final price with the discount.

@helper RenderDiscountedPrice(decimal price)

{

    Buy now for only <strong>$@(GetDiscountedPrice(price))</strong> with $1.00 off!

}

Alternatively, if you want to also use functions in a helper for doing calculations, providing logic, etc.…you can.   Here’s a code sample showing the same code but rewritten to include a function:

@helper RenderDiscountedPrice(decimal price)

{

    Buy now for only <strong>$@(GetDiscountedPrice(price))</strong> with $1.00 off!

}

 

@functions {

    public static decimal GetDiscountedPrice(decimal price)

    {   

        return price-1// just a dollar off, we’re cheap

    }

}

All that’s needed for a function library is the @functions declaration with braces to signify the beginning and ending of the code block.  Many functions can be placed here and the function signatures have the exact syntax as if they were in a standard .cs file.  The calling syntax,HelperFileName.helperName([args…]); is a combination of the filename without the extension but with the name of the helper instead. Using default.cshtml located at the root of the web site, locate this block of code…

<div id=”featuredProduct”>

    <img alt=”Featured Product” src=”@HrefAttribute(“~/Images/Products/” + featured.ImageName) />

    <div id=”featuredProductInfo”>

        <div id=”productInfo”>

            <h2>@featured.Name</h2>

            <p class=”price”>$@string.Format(“{0:f}”, featured.Price)</p>

            <p class=”description”>@featured.Description</p>

        </div>

        <div id=”callToAction”>

            <a class=”order-button” href=”@HrefAttribute(“~/order”, featured.Id) title=”Order @featured.Name“>Order Now</a>

        </div>

    </div>

</div>

and replace it with this block of code (the highlighted code is the modifications necessary)…

<div id=”featuredProdcut”>

    <img alt=”Featured Product” src=”@HrefAttribute(“~/Images/Products/” + featured.ImageName) />

    <div id=”featuredProductInfo”>

        <div id=”productInfo”>

            <h2>@featured.Name</h2>

            <p class=”price”>

                @{var price = featured.Price;}

                $@string.Format(“{0:f}”, price) <br/>

                @Pricing.RenderDiscountedPrice(price) // HelperFile.HelperName syntax/behaves like a static

            </p>           

            <p class=”description”>@featured.Description</p>

        </div>

        <div id=”callToAction”>

            <a class=”order-button” href=”@HrefAttribute(“~/order”, featured.Id) title=”Order @featured.Name“>Order Now</a>           

        </div>   

    </div>

</div>

The code’s been changed to declare a variable named price and set it to the featured product price, which is then to be used in the following two lines of code, including the existing line that renders the price.  The variable is available to all parts of the web page below where it’s declared by default. (you can modify a variable’s scope if need be).  Anywhere in the Bakery site that you want to include a message about the discount, you can use the same single line call to produce the same message about the discount.

4. Verify the Results

Run the default.cshtml file and check that the sales message has been rendered.

image_8

When using WebMatrix as the tool for creating helpers, you can release helpers only as .cshtml files into \App_Code folders across projects (at this point in time, and subject to change).  If you need to release .dll files, you can create helpers in Visual Studio 2010 and package them with NuPack if you’re creating something sharable or as a private .dll otherwise.