Exercise 3: Creating and Consuming Razor Helpers

ASP.NET Web Pages Helpers are components that provide certain functionality, and can be accessed by any Razor or ASP.NET Web Page by using a single line of code. You can build your own helpers, which are stored as .cshtml|vbhtml razor files, or use the built-in helpers from ASP.NET or Razor.

Using helpers will increase your code reusability, organization and maintainability because you will be creating separate units for specific features. In addition, you could take advantage of built-in or third party helpers to easily interact with multimedia, social networks, security, email and data grids.

In this exercise, you will learn how to consume and create Razor helpers in your solution. To do that, you will first use a WebImage helper to display images with watermarks, and then you will use a WebGrid helper to show the album data. At the end, you will create a custom helper with Razor syntax to show the current date.

Task 1 – Consuming the Razor WebImage Helper

In this task, you will learn how to use Razor WebImage Helper to display an image and add a watermark on it.

Note:
WebImage Razor Helper provides functionality to manage images in your page.

The usage of WebImage helper requires two steps:

1. You need to work with Razor syntax and create a variable that will contain the image:

@{ var myImage = WebImage("/Content/myImage.jpg")

// Work with the image…

}

@Code Dim myImage = WebImage("/Content/myImage.jpg")

 ' Work with the image…

End Code

2. Then, in order to load the image in the page, you have to show the variable that contains the image inside an HTML <img/> tag:

<img src="@myImage"/>

Here you will find a reference of the additional WebImage Razor functions that are available:

- WebImage(string Path):Loads an image from the specified path.

- WebImage.AddImagesWatermark(string Path)

- WebImage.AddTextWatermark(string text): Adds the specified text to the image.

- WebImage.FlipHorizontal()/WebImage.FlipVertical(): Flips the image horizontally /vertically.

- WebImage.GetImageFromRequest([opt]string postedFileName):Gets and image from request after being posted.

- WebImage.Resize(width, height):Resizes the image to the size specified in pixels.

- WebImage.RotateLeft() /WebImage.RotateRight():Rotates the image left / right.

- WebImage.Save(path):Saves the image to the specified path.

You can find more information about Razor WebImage Helper in ASP.NET Web Pages with Razor Syntax Book Beta.

  1. If not already open, start Microsoft Visual Web Developer 2010 Express from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Web Developer 2010 Express.
  2. In the File menu, choose Open Project. In the Open Project dialog, browse to Source\Ex03-CreatingAndUsingHelpersInRazor\Begin, select MvcMusicStore.sln and click Open.
  3. Open Index.cshtml|vbhtml view at Views/Home project folder and add WebImage Helper logic to load an image and save it in a different location. To do this, you will first use WebImage() to load an image inside a variable:

    cshtml

    @model dynamic
    FakePre-20a5c0a49b404e228ff8dadc7e367cd4-b2768e8190874c68a771ac4cbac2f5f1FakePre-b4fdc04325a841edb9383a2888385523-0e6edfc9223546b7b3bbae661853e006FakePre-0f4f6ad4bdc94793b07005b05cb207b4-5e88919e71ad47e0982a8ebb42a0f4cbFakePre-324ae9ba17ad4d7daa3fade8ed50d663-6e8a365fa16c45db8df859ae26f8e7fdFakePre-6de192f6fa834153bc0345e6cff24e35-b9d70020ab824aaca614abfb69d9f80fFakePre-b2f13576133e4a0aa9fe5652fc6f4518-abf3f56426c04e929cc372a0084e905dFakePre-622f723336e64242b1f169f1d954d5e9-10e702b3a2d6418a9fcbf6ba19be8bfcFakePre-c9fa4f6c19894de193c56d0e07d27b71-f164246544b3481db9218ee427d353a9@{ var image = new WebImage(@"~\Content\Images\home-showcase.png"); var imagePath = @"Content/Images/newimage.png"; var saveImagePath = @"~\Content\Images\newimage.png"; image.Save(saveImagePath); } <img src="@imagePath" alt="image with watermark"/>

    vbhtml

    @modeltype Object
    FakePre-2992a0e4d75348759dea38cc2bc0871a-8588fc382fa3439bb35e7c7cb337e6ceFakePre-94b9b212e16744d481ac0f6e9709e8b7-164e5b98fc094ababa19ff96593e5716FakePre-4721803293874d94b83ffa7ffa9ca9d3-9ab4dbf3c74847f481875aba941c41afFakePre-39f99ab6139a45c483212e2246bcfe36-06075d153a204429833a35f4c8c36cd7FakePre-4435c34d695f4df0a79f56a7bb6e2aae-811770691eda42a5a36ccbd3169320c6FakePre-71b5c740dfe944988249e8470e667180-ad097412285641a4a3df8d1ff58da61dFakePre-0d52efbafbba40fc8c4c3816bfa37380-763478d8b0914624a00b5d0fc08d4e8eFakePre-485d597514444402a7785b306f37d1f9-a3d737bcdf854d8aa4ff2f820da8222d@Code Dim image = New WebImage("~\Content\Images\home-showcase.png") Dim imagePath = "Content/Images/newimage.png" Dim saveImagePath = "~\Content\Images\newimage.png" image.Save(saveImagePath) End Code <img src="@imagePath" alt="image with watermark"/>

    Note:
    ImagePath separator character is “/” to allow browser compatibility.

  4. Add a watermark to the image by using AddWatermark() method:

    cshtml

    FakePre-a03a85787c4d4950b728ece12e889d1b-4ec76e1a2e8547179c4f089e8b8838eaFakePre-7d656f5d87e14862807573ab7213b4b9-7b998b870cf94ee99422de0428ffe5db image = image.AddImageWatermark(@"~\Content\Images\logo.png", horizontalAlign: "Left", verticalAlign: "Top");FakePre-69efabc6f694422b9c0720a2af2fb0b1-e234d39703334fd9bb825bcdc88bb3e3FakePre-718e2fe6feed4ae4a9e84e8360b72f43-148e8894de7c4d68b4ba6d727eeb2189FakePre-431a656862f74570ad0d5e3643256085-d53394d53647435da9cc51a61ff8c78eFakePre-781dec6b5db34b799a358bf6be413643-2a81468f77854f94bc1988a5abbc585aFakePre-71f16ecafede44e1a005de6c8ca93c2a-3d45cfe32b8946a3be1e1afbbe66060c

    vbhtml

    FakePre-0dbfd5a04a434a0fa0c86f025e3b8758-dd6df78495584c8e814e88a2b4f17d50FakePre-f00875a6923a4f6ea7703e0bfc58488e-a6eb3ac1df0d4aad952252b3e4af4736 image = image.AddImageWatermark("~\Content\Images\logo.png", horizontalAlign: "Left", verticalAlign: "Top")FakePre-b004a292c72f4466b464f6764ebf3a83-ddb0620bd8204d9e9ac10b3dbc3bbbedFakePre-00867ce4ce544eac94ca2b029f7c6a0f-c9c7fdc81fbc4664b5f370e4386a1301FakePre-dd572533baf643f88b22f9331902f60f-fa4ba012072a405388bb24b1d22c6afeFakePre-a37083a3f10a44e583dbbf3d568d9c0d-63588246722c4f4ab5ac263bab12b9d9FakePre-7d4fe84ca7e747779d45967b2eaf9a21-ced5bfd9e73b47489726d9f85d102454

    Note:
    AddImageWatermark method accepts more parameters than the ones used here, which are optional and provide a default value. Here is the complete method definition:

    C#

    AddImageWatermark(

    string watermarkImageFilePath,

    string format (optional, default is null),

    int width (optional, default is 0, in pixel units),

    int height (optional, default is 0, in pixel units),

    string horizontalAlign (optional, default is "Right"),

    string verticalAlign (optional, default is "Bottom"),

    int opacity (optional, default is 100, in percentage),

    int padding (optional, default is 5, in pixel units)

    );

    Visual Basic

    AddImageWatermark(String watermarkImageFilePath,

    String format (optional, TypeOf default Is Nothing),

     Integer width (optional, TypeOf default Is 0, in

    pixel units),

    Integer width (optional, TypeOf default Is 0, in

    pixel units),

    Integer height (optional, TypeOf default Is 0, in

    pixel units),

    String horizontalAlign (optional, TypeOf default Is

    "Right"),

    String verticalAlign (optional, TypeOf default Is

    "Bottom"),

    Integer opacity (optional, TypeOf default Is 100, in

    percentage),

    Integer)

Task 2 – Running the Application

In this task, you will run the application to verify that the image with the watermark is loaded.

  1. Press F5 to run the application.
  2. The application starts in the Home page and displays the image with the watermark:

    Figure 22

    Image and watermark using Razor WebImage helper

Task 3 – Adding a WebGrid Helper to Browse View

In this task, you will add a WebGrid helper to show a grid of albums inside Browse view.

Note:
The WebGrid Helper renders an HTML table that displays data from the model or from a database. It supports data formatting, paging and sorting.

It generates a collection of Columns and parameters within the given data source, which is rendered as an HTML table that can be accessed after the grid is generated.

To use a grid from a model, you will first need to generate the grid and assign it to a variable with the WebGrid creation method, which receives the model data structure as a required parameter:

C#

@{

var grid = new WebGrid(Model.Elements);

}

Visual Basic

@Code

Dim grid = New WebGrid(Model.Elements)

End Code

Then, to render the grid in the page you will have to use a GetHtml() method:

@{

var grid = new WebGrid(Model.Elements);

grid.GetHtml();

}

Visual Basic

@Code

Dim grid = new WebGrid(Model.Elements)

grid.GetHtml()

End Code

Here you will find method references if you want to use additional features:

C#

WebGrid(dynamic IEnumerable<object> source (required field),

IEnumerable<string> columnNames (default is null),

string defaultSort (default is null),

int rowsPerPage (default it 10),

bool canPage (default is true),

bool canSort (default is true),

string ajaxUpdateContainerId (default is null),

string fieldNamePrefix (default is null),

string pageFieldName (default is null),

string selectionFieldName (default is null),

string sortFieldName (default is null),

string sortDirectionFieldName (default is null)

);

Visual Basic

WebGrid(dynamic IEnumerable(Of Object) source (required field),

IEnumerable(Of String) columnNames (TypeOf default Is Nothing),

String defaultSort (TypeOf default Is Nothing), Integer rowsPerPage

(default it 10),

Boolean canPage (TypeOf default Is True),

Boolean canSort (TypeOf default Is True),

String ajaxUpdateContainerId (TypeOf default Is Nothing),

String fieldNamePrefix (TypeOf default Is Nothing),

String pageFieldName (TypeOf default Is Nothing),

String selectionFieldName (TypeOf default Is Nothing),

String sortFieldName (TypeOf default Is Nothing),

String sortDirectionFieldName (TypeOf default Is Nothing))

C#

WebGrid.GetHtml(string tableStyle (default is null),

string headerStyle (default is null),

string footerStyle (default is null),

string rowStyle (default is null),

string alternatingRowStyle (default is null),

string selectedRowStyle (default is null),

bool displayHeader (default is true),

bool fillEmptyRows (default is false),

string emptyRowCellValue (default is null),

IEnumerable<WebGridColumn> columns (default is null),

IEnumerable<string> exclusions (default is null),

WebGridPagerModes mode (default is 3),

string firstText (default is null),

string previousText (default is null),

string nextText (default is null),

string lastText (default is null),

int numericLinksCount (default is null)

);

Visual Basic

WebGrid.GetHtml(String tableStyle (TypeOf default Is Nothing),

String headerStyle (TypeOf default Is Nothing),

String footerStyle (TypeOf default Is Nothing),

String rowStyle (TypeOf default Is Nothing),

String alternatingRowStyle (TypeOf default Is Nothing),

String selectedRowStyle (TypeOf default Is Nothing),

Boolean displayHeader (TypeOf default Is True),

Boolean fillEmptyRows (TypeOf default Is False),

String emptyRowCellValue (TypeOf default Is Nothing),

IEnumerable(Of WebGridColumn) columns (TypeOf default Is

Nothing),

IEnumerable(Of String) exclusions (TypeOf default Is

Nothing),

WebGridPagerModes mode (TypeOf default Is 3),

String firstText (TypeOf default Is Nothing),

String previousText (TypeOf default Is Nothing),

String nextText (TypeOf default Is Nothing),

String lastText (TypeOf default Is Nothing),

Integer numericLinksCount (TypeOf default Is Nothing))

  1. Open Browse.cshtml|vbhtml view at Views/Store project folder.
  2. Create a WebGrid that uses the model to show the albums. Additionally the grid will be sorted by name and show 10 elements. To do this, you will create the grid using Model.Albums and two extra parameters: defaultSort and rowsPerPage.

    cshtml

    @model MvcMusicStore.ViewModels.StoreBrowseViewModel
    FakePre-a8fe991e29354db6b2d6c52b65b08d98-bd8e0c6af9904bdc905e8b7cd52da091FakePre-d8e48f8c9a8641e0961ec16ff09648bb-7598988d0b45493ca61386bdaaaf3dc1FakePre-8a155933c25045f5ab200f0c58f025df-2181df615419480f9e7a22caec89d155FakePre-888ea2281b0b4ad9b5be923d1d8df5d3-bfdb43a6054343368712a9092cd73c21FakePre-4203df7257494198bc03222787285d0c-f28d9d2e9f1f4d56989e2c18b80ee74dFakePre-268e4eeb6e5345109e1415391e4560f5-d31ff838ff6046a88b1805a793faf36d@{ var grid = new WebGrid(Model.Albums, defaultSort: "Name", rowsPerPage: 10); }

    vbhtml

    @modeltype MvcMusicStore.ViewModels.StoreBrowseViewModel
    FakePre-efb9ebae3f9249859d16b12d03ebe122-038f10d341dc429184a585b583f9dc5eFakePre-8c19381753f247b7a23473c4e61709d0-b1c4173bcc85408894e22a11d8588e95FakePre-ddfb4873038a4d6fbcca00ebfab1afdc-c04377e21f7548948b6a53dabe3488e0FakePre-08e6b1c1e5524ef697ad8a4d2508f4fa-afb3c99c17bd4fbf92c51d382eea3060FakePre-875aa2c196124231b722bfe3ada82e53-c33ea19a65e24d3fb0f7d51ccff1f673FakePre-1de98fce008d449982ed77b033ab68b6-19233e30e85a4ba6af213f9d357665c4@Code Dim grid = new WebGrid(Model.Albums, defaultSort:= "Name", rowsPerPage:= 10) End Code

  3. Display the WebGrid specifying two values in the Column collection: Title and Artist.

    cshtml

    @model MvcMusicStore.ViewModels.StoreBrowseViewModel
    FakePre-8d96042be3b746ca918fcf4bf8066524-f99bee889a724161bde30e14c9c2623dFakePre-bfa3a8253ab24e1d9294d78e6c5c1020-a1cb40adc274499babdcd98672c7dca3FakePre-0d1a1e3736104f5ea0c5af584698a8da-c283d32e4fe1430d832003936cdb84ceFakePre-4a30ca12ddd44ae28059d4efff2b0401-58eb6406e24c4836870182cefc2b182aFakePre-ad79f455a60a420abbc049ba1a31881e-c8caae0df85343d289e44d9063435e39FakePre-9c15dd593021472896175ab9f3858bdc-f4f1032643b3464f9626997b06896db9FakePre-9b87acadb285499cbcbaa191776a13fa-80ddc19eda994aca94b822437bdf0289FakePre-ed3f564de0a14d4bba41c8f5c71aa7fb-15140e7b28854458b2c7355752338937FakePre-31fce0e4352a4989be35abd021a58c2c-4ff17847b4904e67b931082107611550FakePre-7d9f81471e09411d80b011ed0d17d806-8a8ceac23e784520bb5be3b293646ea2@grid.GetHtml(columns: grid.Columns( grid.Column("Title"), grid.Column("Artist") ))

    vbhtml

    @modeltype MvcMusicStore.ViewModels.StoreBrowseViewModel
    FakePre-f73c730c04ce4ff390941801ef7bbcc0-28f586ea4749491587b8f9276a7abe03FakePre-582e8921429c44bd97bce05fcb200028-cb69ed124d0743dcb20d9c82c44f095fFakePre-bdc603b7e12e4ed890261d07e4b72a89-afb9915d0fc44435b6412f25188fbe02FakePre-9df9c6904d9f4052a1496da0fde3d3f6-0d1c1c7970194f7980d46ec5722b6c78FakePre-b8f2088069cc46d6bed7241355694f74-5a46f9551c9c4012b26158e61a67ce04FakePre-4563d5ec74194be0aaae5275b506a69a-11e0bdd778004623b5e8334fb3af88fcFakePre-a2dd99c34551471288dd97c8ab0eaaca-1ddffc31f84d4267ad6d87363a850cb0FakePre-53b28871329d454c8409727ba0c4848b-56fed89c62e64021ba6885c43c8fdd03FakePre-f426eb57dc43432e96eedc36dee7228d-2183f072da63472291bb54479ce35b41FakePre-d731f970361d40a7a9b0ca7dc66f3d38-10410f50b83747dd92ac1b8bfa7cf016@grid.GetHtml(columns:= grid.Columns( grid.Column("Title"), grid.Column("Artist") ))

Task 4 – Running the Application

  1. In this task, you will run the application to verify that the WebGrid is loaded and shows album data as expected.
  2. Press F5 to run the application.
  3. The project starts at Home. Change the URL to /Store/Browse to verify that the Browse view loads the WebGrid as configured in the last steps:

    Figure 23

    A Razor WebGrid showing the albums

Task 5 – Creating a Custom Helper

  1. Up to now you have been using Razor third party helpers. In this task, you will learn how to create your own custom helper in Razor. In order to do that you will add to the solution a helper with the name “ShowTime()” that will show the current date and time.
  2. Add a new element into App_Code by doing right-click on App_Code folder, and selecting “Add|New Item”.

    Figure 24

    Adding a new item into App_Code

  3. In the Add New Item dialog, select from MVC 3 templates, MVC 3 Partial Page (Razor). Use the name MyHelpers.cshtml|vbhtml and click Add. This will create an empty Razor file with the name MyHelpers.cshtml|vbhtml.

    Figure 25

    Adding a new Razor Helper – C#

    Figure 26

    Adding a new Razor Helper - VB

  4. Open MyHelpers.cshtml|vbhtml and declare the helper:

    cshtml

    @helper ShowTime(){ }

    vbhtml

    @helper ShowTime() End helper

  5. In ShowTime helper, include HTML code to show current date. To do that, you will use the @DateTime.Now code inside an HTML markup block:

    cshtml

    @helper ShowTime(){
    <div> Current Time is @DateTime.Now </div>FakePre-c42126eff6734f398d787b6848b1ed9a-6eaf7be2eb20408f8393f174ade10557

    vbhtml

    @helper ShowTime()
    @<div> Current Time is @DateTime.Now </div>FakePre-0a9e23d7003740f3b887004e495237cc-95f6d91282d1427385d2ef8fcc42676d

  6. Open Index.cshtml|vbhtml View in the project folder Views/Home to call the helper:

    cshtml

    @model dynamic
    FakePre-e7fc2d07c0e7475f88a076b587a57002-f93c141469364f5fb25d4f26af6b0204FakePre-2c2e576a3fbc455c9a1d35d85b04b8fd-eecd93006a0d4c97aa3c4bb88691e31bFakePre-56cf610cbe444f60b4fb444f5e6a6b99-affce6ccc3d74e6ba91aa184b72d986dFakePre-ee736dfc61994d94960d03766e579a93-f3ea81dcaf7043f38832f0401cbcf493FakePre-6878d5b9f9a24316bf71153d1c4e69a9-173f01473e6246c7a0abd27de7bd03fdFakePre-3a29cb9a50e146778344ef4c07e7df21-9b4ad2719b724b7b834af8d151585b9cFakePre-9f39f2d394514f9cb9db5b28b56e0663-e4ab3502eb834675adc608874692083cFakePre-0353302057a243e0847f43b7b480e3fb-ba2d2775d82044cc9dfe9b6878ee5bda@MyHelpers.ShowTime()FakePre-f3d1eafd3b28457891ab28771e693ec5-a7f3c88bc641404a9492277e8847de17FakePre-fd8d26575ddd4b7ead3ccdf9feab810a-035479f04360471badc22d18a74a3947FakePre-13121dcbc21b4947865b9945422d7484-0efd7afe3d254559a0a56a55cd73c2a5FakePre-07e62755e6374f8b9bfa12d8d753895a-5c1a3bf5ed274f068e82a2a691752923FakePre-99874e8e947d45c3bdb6cc804647b94b-a0ab653098b340088db8003db27e797cFakePre-9c34ef41522f4b89ab51810ea15472cb-ede7ec6cb8444e9199b40502f438c238FakePre-a7c9f56729d941b3b84a6b535c480d64-93684d6bb25b4c23bde4bbb5a3579082FakePre-01b2e76d8e414b03bc0da00d5428f809-4b16bcc76afd47a38fbd7feb826b44bbFakePre-508135080ec94ee9b06a12d607862f4e-4b8b2184cf214629bed7e3c0da7494f8

    vbhtml

    @modeltype Object
    FakePre-0cc67a998d294024a2d5dff16650cd8b-02d44079a680466db582caef3d003908FakePre-6e9543f71b5c4c5a8e3e39a4c529e254-7bee4acfecc9451baed56d9b9acc787aFakePre-47e8c1f6966844f69ee40277fb84f94e-e083ffe0a906419eb393e16040c656bdFakePre-0ec354988b71432295ba6fe89be122a1-858cd88074b24fbe9383971613117234FakePre-423a4b99992d4cefa3cfad2314c97801-e231124dd17c411d89c9a1dcaaea5de7FakePre-088f1ad2e13446668cb7b911e5b8febd-7acad53f77ee4ed7a7925bbc22292e8eFakePre-24b23261d2f74fb3a07c08aaf6dddf27-dbecd0bf568e4b22b26c9e98651889bbFakePre-7162159477cc4c7cb370ee084a5f2494-d055e1f0650a4c4193cc72bfb093d431@MyHelpers.ShowTime()FakePre-4010a80daa8046bb898ecbefb12672a3-1869c4d7155f4076b3d7c44241aab0c5FakePre-e0abc099e7204c9883944af5a0388428-45453ca277db4b44afbd41afc322d438FakePre-62dfc67490f5429e88ef33b3a3d3953a-5ef4042a9a244cc888e54dd54edbb736FakePre-1172283de8574d26a76707b60b6bbf91-538d736caf784419ab0c12cce0e9a355FakePre-26d4b64daa6f4a9c84944fc9262d1446-5cf84bdee60c462daffb692203bf5facFakePre-a7947e63d56d415285c70f92d426721d-cdc113f985fc4c40ba22bbdfc3818dd1FakePre-388fc45c545d44a5810656ac91a2ee06-cafc1ce26a40449a84bc610914e27847FakePre-f6285ee0439d415490a3c2f8368380c0-efa7b1beb440432e89205e66b38d1713FakePre-b6c1dcc8b37f4125aa97f8d750c00e04-1cf955d6e2c2418e90e84f1e5f83429a

Task 6 – Running the Application

  1. In this task, you will run the application to verify that the helper is working as expected.
  2. Press F5 to run the application.
  3. The project starts at Home:

    Figure 27

    Current time displayed with a custom helper

Next Step

Summary