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)

Models in Razor (Must know)


In this recipe, I will introduce you to the Razor model directive by comparing it with the @inherits directive, and then we'll set up a model class to show you how to scaffold views and also how to add views manually.

Getting ready

The @model directive announced with the release of ASP.NET MVC 3 Beta provides a cleaner and more concise way to reference strongly-typed models from view files than the @inherits directive, which was announced with the first ASP.NET MVC 3 preview.

In MVC, we can have strongly-typed views or loosely-coupled views, the main difference between the two being that strongly-typed views give us the benefit of IntelliSense; on the other hand, IntelliSense is not available with loosely-typed views.

To learn more about @inherits and @model directives, let's create a new data model class and scaffold the CRUD views using Code First Approach in Entity Framework. The goal of this model will be to allow the user to create and manage a To-Do list.

  • Entity Framework (EF) is an Object-Relational Mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing and storing the data in the database and working with the results in addition to DataReader and DataSet.

  • Code First Approach provides an alternative to the Database First and Model First approaches to the Entity data model and creates a database for us. This enables a pretty sweet development workflow and lets you define model objects by simply writing classes.

How to do it...

Model manages the behavior and data in the application and responds to requests for information. So, let's create a sample model to manage a To-Do list.

Creating a data model class

Right-click on the model folder and add a class file called ToDo.cs and add the following code:

In this code, I have added four properties: ToDoId, Title, Description, and IsDone. I have added the [Required] attribute with the property Title and Description, which specifies that a data field is required. I have also added [DataType(DataType.MultilineText)] which specifies that the data field is multiline. So, these are declarative validation attribute rules which will automatically be enforced whenever ASP.NET MVC performs model binding operations within an application. Remember to add a namespace, System.ComponentModel.DataAnnotations, at the top of the file. In addition with the validation attribute I have also used a [DisplayName("Is Done")] attribute with the IsDone property, and this will display "Is Done" instead of "IsDone" on the view. This attribute is derived from the System.ComponentModel namespace.

Data annotations help us to define the rules with semantic attributes such as [Required], [DataType], and [DisplayName] to the model classes or properties for data validation and displaying suitable messages to the end users.

Scaffolding view templates

Scaffolding is a technique used in MVC to quickly generate views, controllers, databases, table scripts, and so on, and allows us to Create, Read, Update, and Delete records (also known as CRUD) with the help of Entity Framework.

When you are done with the model, build the solution from the Build menu. Now, right-click on the controller folder to add a new controller. The following dialog box will appear:

In the Add Controller dialog box, use the controller name to ToDoController. I am going to scaffold the CRUD views using Entity Framework, so select the appropriate template and model class as shown in the preceding screenshot. Also, we don't have any data context as of now, so add a new one from the drop-down list. At the end, click on the Add button and this will add all the CRUD views and controllers on the fly.

Run the application and navigate to the ToDo controller and try creating a blank entry; you will see the validations in action.

Now, create your To-Do list. In the following screenshot, you can see that I have added four To-do items. You will notice that the title name for the IsDone column is Is Done (with space), this is because of the [DisplayName("Is Done")] attribute that we have added with the model property.

Now, we are all set to learn the @inherits and @model directives.

@inherits and @model directives

Open the Index.cshtml file from the Views/ToDo folder and look at the first line of code, highlighted in the following screenshot:

The code line @model IEnumerable<MvcApplication1.Models.ToDo> is very similar to @inherits System.Web.Mvc.WebViewPage<IEnumerable<MvcApplication1.Models.ToDo>>. So, using @inherits System.Web.Mvc.WebViewPage<IEnumerable<MvcApplication1.Models.ToDo>> at the top of the file works fine but it is a little verbose. So, it is more common to use @model IEnumerable<MvcApplication1.Models.ToDo> at the top of the file and then you don't need to have @inherits or specify a view base class anymore; this is power of Razor.

Now, once you have the model on the view, we can do anything. For instance, to display the first To-Do item I could write the following code:

It will also display the first To-Do Title and Description.

This is all about the new @model directive. We have scaffolded all the required view templates till now, however, we can manually add the different views one by one, but before doing this I will recommend you to delete the ToDo View folder with all its views to avoid delicacy. Let's learn them now.

Manually adding view templates

First, to display the list of To-Do items we need a controller action that we already have. Open ToDoController from the Controller folder, and you will see the following code:

In the first highlighted rectangular region, we have an instance of the database context, and in the second region we have an action method called Index which will return the list of To-Do items. Now, to add the view for this Index action method, we need to right-click inside this method and select Add View..., as shown in the following screenshot:

When you click on Add View..., you will see the following dialog box:

In the Add View dialog box, remember to check the Create a strongly-typed view checkbox, select the ToDo model class, and set the Scaffold template option to List. When you are done, click on the Add button. This will create exactly the same Index.cshtml view page that the earlier scaffold does. In the same way, we can scaffold views for Details, Create, Edit, and Delete action methods.

If you open the Index.cshtml view page, you will see the following code:

In this code, for each modelItem I'm creating one <tr> and four <td> tags that will display Title, Description, IsDone, and Edit/Details/Delete links.

There's more...

If you open the CRUD views that we created earlier, you will see many HTML helpers that are being used, and in the next recipe we will look at helpers used in Razor.