Book Image

Instant Razor View Engine How-to

By : Abhimanyu Kumar Vatsa
Book Image

Instant Razor View Engine How-to

By: Abhimanyu Kumar Vatsa

Overview of this book

Razor View Engine is an advanced view engine from Microsoft. Razor View is one of the most popular view engines which doesn't require you to explicitly close the code block. This book will help you understand and configure RazorView in your system to create dynamic web pages. Instant Razor View Engine How-to will help you to make your application more MVC friendly with clean, lightweight code which is quicker and easier to understand compared to other view engines. Instant Razor View Engine How-to introduces you to methods to make your web application more MVC friendly. The book begins by detailing the anatomy of RazorView Syntax and configuring Razor View as well as creating a web application project which will also help you to select an appropriate programming language. The later section of the book goes on to discuss creating view templates and creating View pages using Razor syntax. By the end of the book, you will also be familiar with Razor directives, helper components, and work with Partial views to reuse razor code throughout the application.
Table of Contents (7 chapters)

Razor helpers (Must know)


In this recipe, you will learn how to create helpers with the extension method as well as with the declarative @helper syntax. In addition to this, we will see a list of the most frequently used standard helpers such as input helpers, link helpers, form helpers, label helpers, and validation message helpers.

Getting ready

The previous versions of MVC introduced an extension method of the HtmlHelper class that allowed you to define new helpers. In MVC 3 you have an option to continue doing that, however you can also use a declarative helper using the @helper syntax within a Razor view. So, first you will look at the extension method approach and then we will look at the @helper syntax approach, and at the end we will also look at the other standard helpers.

How to do it...

This recipe is going to focuses completely on helpers so let's begin by creating a helper with the extension method.

HTML helpers using the extension method

The new HTML helpers created by the extension method of the HtmlHelper class work just like the standard HTML helpers (at the end of this recipe you will learn about standard HTML helpers). Let's recall, in the last recipe we created a To-Do list, shown in the following screenshot:

I need to safeguard myself when the Description area gets very long, which can break the look of my page. Thus, I need to truncate the description message by setting the maximum length, say, to 40 characters to be displayed, and when the maximum length is crossed it should display …more at the end. To see more of the description, the user should click on the Details link. The following screenshot shows the output screen:

In the preceding screenshot you can see the …more character is truncated at the end of the first To-Do item description. This can be done using the extension methods. Let's develop this by adding a new class named HtmlHelpers.cs.

In the preceding screenshot, we added an extension method to the HtmlHelper class named Truncate(). There are a couple of things that you should notice about this class. First, notice that the class is a static class. You must define an extension method with a static class. Second, notice that the first parameter of the Truncate() method is preceded by the keyword this. The first parameter of an extension method, which is this HtmlHelper helper, indicates the class that the extension method extends to and it is derived from the namespace System.Web.Mvc. This Truncate() method will accept two parameters, the input string and length. In the method body, We need to check if the length of the input string is less than or equal to the length. If it is then keep it as it is, or else return the substring of the input string by concatenating …more in the string. Let's see how the view page will utilize this extension method:

To bring the scope of the newly-added extension methods on a view page we have added the MvcApplication1.Helpers namespace; alternatively, we can also add this namespace directly into web.config to use it in a whole application. Now, instead of using @Html.DisplayFor(), I would use my extension method @Html.Truncate() and pass two parameters item.Description, which is string and 40, which is a int value and I'm done.

Now, what if I want to display …more in red color? The extension method returns a string value so we can embed the HTML markups in that string.

In Razor, the @ character is HTML encoded by default for better protection against XSS attacks. Thus, on the view page we will use the @Html.Row() helper:

Now, you will have the desired output on your screen.

All this can be done by simply using declarative @helper syntax, let's learn it.

HTML helpers using the @helper syntax

In Razor, we can declare the @helper syntax on the same view page or create it in a separate file. First we will see how to declare it on the same view page.

In the previous screenshot, I declared @helper by the name Truncate, which will accept only two parameters, the input string and length. To call this @helper Truncate(), you just have to use @Truncate(item.Description, 40). That's all.

Now, if you want to move @helper Truncate() into a separate file, we can do this by adding a new .cshtml view page file inside the App_Code folder and paste all the @helper Truncate() code, and at the end call @helper Truncate() using @HtmlHelpers.Truncate(item.Description, 40).

If you run this application, you will have the same output.

So far in this recipe you learned how to create HTML helpers with the extension method and with declarative @helper syntax. Now, let's learn about some standard HTML helpers.

Standard HTML helpers

The HTML helpers that we have seen so far in this recipe return a string, and that string can represent any type of content that you want on the view page. The main purpose of any HTML helper is to create small blocks of HTML, and that can be categorized into input helpers, link helpers, form helpers, validation messages helpers, label helpers, and more.

Input helpers

Razor includes a set of standard HTML input helpers; I have listed some of them in the following table:

HTML helper

HTML element

Short description

@Html.CheckBox(s:name, b:checked)

<input type="checkbox" name="name" id="name" checked="checked" />

Returns a checkbox input element.

@Html.CheckBoxFor(e:expression)

<input type="checkbox" name="name" id="name" checked="checked" />

Returns a checkbox input element for the model.

@Html.DropDownList(s:name, list:selectlistitems)

<select name="name" id="name"></select>

Returns a single-selection select element.

@Html.DropDownListFor(e:expression, list:selectlistitems)

<select name="name" id="name"></select>

Returns a single-selection select element for the model.

@Html.Hidden(s:name, o:value)

<input type="hidden" value="value" name="name" />

Returns a hidden input element.

@Html.HiddenFor(e:expression)

<input type="hidden" value="value" name="name" />

Returns a hidden input element for the model.

@Html.ListBox(s:name, list:selectlistitems)

<select multiple="multiple" name="name" id="name"></select>

Returns a multi-select select element.

@Html.ListBoxFor(e:expression, list:selectlistitems)

<select multiple="multiple" name="name" id="name"></select>

Returns a multi-select select element for the model.

@Html.Password(s:name, o:value)

<input type="password" value="value" name="name" />

Returns a password input element.

@Html.PasswordFor(e:expression)

<input type="password" value="value" name="name" />

Returns a password input element for the model.

@Html.RadioButton(s:name, o:value, b:checked)

<input type="radio" value="value" name="name" checked="checked" />

Returns a radio button input element.

@Html.RadioButtonFor(e:expression, o:value)

<input type="radio" value="value" name="name" checked="checked" />

Returns a radio button input element for the model.

@Html.TextArea(s:name, s:value)

<textarea name="name">value</textarea>

Returns the specified textarea element.

@Html.TextAreaFor(e:expression)

<textarea name="name">value</textarea>

Returns the specified textarea element for the model.

@Html.TextBox(s:name, o:value)

<input type="text" name="name" value="value" />

Returns a text input element.

@Html.TextBoxFor(e:expression)

<input type="text" name="name" value="value" />

Returns a text input element for the model.

If you look at the list of Input helpers, you will notice that each helper has two versions such as CheckBox and CheckBoxFor, TextBox and TextBoxFor, TextArea and TextAreaFor.

Helpers such as CheckBox, TextBox, and TextArea work fine but they don't allow coding in the strongly-typed fashion and you need to hardcode whatever name you want as the first argument:

@Html.TextArea("Description")

So, in Razor we have a model version of helpers such as CheckBoxFor, TextBoxFor, and TextAreaFor that require a strongly-typed view and use the view model:

@Html.TextAreaFor(model => model.Description)

The helpers will use the lambda expression to infer the name and the value of the view model passed to the view. And because it is a good practice to use strongly-typed views and view models, you should always use the @Html.TextBoxFor helper.

By default, the Create and Edit scaffolds now use the @Html.EditorFor helper instead of the @Html.TextBoxFor helper. The @Html.EditorFor helper works by examining the model type passed to it; for instance, if the model type is Boolean, EditorFor will generate a checkbox; if model type is text, EditorFor will generate an input box. EditorFor also improves the support for metadata on the model in the form of data annotation attributes.

In Razor, sometimes we also use another model version of helpers such as DisplayForModel(), DisplayNameForModel(), EditorForModel(), NameForModel, LabelForModel, and ValueForModel that return HTML markup for every property in the model. Let's look at an example of DisplayForModel():

@*<div class="display-label">
        @Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Title)
</div>

<div class="display-label">
        @Html.DisplayNameFor(model => model.Description)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Description)
</div>*@

@Html.DisplayForModel()

In this code, I commented all the <div> blocks and instead of writing four <div> elements we can achieve the same with the @Html.DisplayForModel() helper, and it works great.

Form helpers

Razor also includes a set of standard HTML form helpers; I have listed some of them in the following table:

HTML helper

HTML element

Short description

@Html.AntiForgeryToken(s:salt, s:domain, s:path)

<input type="hidden" value="token" name="name" />

Generates a hidden form field that is validated when the form is submitted.

@Html.BeginForm(s:action, s:controller, o:values)

<form action="/controller/action/">

Writes an opening <form> tag to the response. The request will be processed by the action method.

@Html.BeginRouteForm(s:routeName)

<form action="route">

Writes an opening <form> tag for the route. The request will be processed by the route target.

@Html.EndForm()

</form>

Renders the closing </form> tag to the response.

@Html.AttributeEncode(s:input)

-

Converts the specified string to an HTML-encoded string.

@Html.Encode(o:object)

-

Converts the specified string to an HTML-encoded string.

The AntiForgeryToken helper is used to prevent Cross Site Request Forgery (CSRF) or XSRF attacks. We put the user-specific token as a hidden field on the form, as given in the following code:

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Profile</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>

Then, an attribute is applied to the controller action, which checks the right value submitted with each Post request.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Profile profile)
{
    if (ModelState.IsValid)
    {

If you view the view source you will notice the following hidden input field with a very long token value.

<input name="__RequestVerificationToken" type="hidden" value="cUcTSMC6k4jcDPan1J-qyv--Tcot4Cu8Nma57-NrbkHc6aaV-TkQeQChgSRWSEplMRtj-bliGHFj6UuwrvpLu6-S8qiWci8yyHusroPuWzciNmLRw5YbyGsp_orI4F_q5XouPcbD0F_keLfbKXdMnqS1ZHce-pars_kMxN-flEI1" />

When the form Post occurs, it compares the issued verification token value on the server and ensures that they match.

Validation helpers

Razor also includes a set of standard HTML validation helpers; I have listed some of them in the following table:

Helper

Short description

@Html.Validate

Retrieves the validation metadata for the specified model and applies each rule to the data field.

@Html.ValidateFor()

Retrieves the validation metadata for the specified model and applies each rule to the data field.

@Html.ValidationMessage()

Displays a validation message if an error exists for the specified field in the System.Web.Mvc.ModelState.Dictionary object.

@Html.ValidationMessageFor()

Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message and HTML attributes.

@Html.ValidationSummery()

Returns an unordered list of validation messages that are in the System.Web.Mvc.ModelStateDictionary object and optionally displays only model-level errors.

Link helpers

Razor also includes a set of standard HTML link helpers; I have listed some of them in the following table:

HTML helper

HTML element

Short description

@Html.ActionLink(s:text, s:action)

<a href="action">text</a>

Creates an anchor tag to a link for a specific action.

@Html.RouteLink(s:text, s:routeName)

-

Returns an anchor element that contains the virtual path of the specified action.

@Html.RouteLink(s:text, s:routeName)

-

Returns an anchor element that contains the virtual path of the specified action.

@Html.Action(s:action, s:controller)

-

Returns the result as an HTML string.

@Html.Partial(s:name, o:model)

-

Returns the result as an HTML string.

Label helpers

Razor also includes a set of standard HTML label helpers; I have listed some of them in the following table:

Helper

HTML element

Short description

@Html.Label(s:text)

<label for="control">text</label>

Returns an HTML label element and the property name of the property that is represented by the specified expression.

@Html.LabelFor(e:expression)

<label for="control">text</label>

Returns an HTML label element and the property name of the property that is represented by the specified expression.

@Html.LabelForModel()

<label for="control">text</label>

Returns an HTML label element and the property name of the property that is represented by the specified expression using the label text.

How it works...

Most of the Razor helpers we learned in this section generate HTML elements on the form, we saw some helpers that do not generate HTML element, rather they bring the HTML content from other partial views. In the next recipe, we will look at the partial views.

There's more...

We learned enough about Razor helpers in this recipe, however, there are a few more helpers. You can find them at http://goo.gl/Ov4DQ.