Wednesday, April 25, 2012

Welcome ASP.NET Razor View - Part 2


The previous part introduces with an Razor web site, which is built on top of Razor view engine. This part will cover some basic Razor stuff which would be kind of essentials to know, in order to develop an Razor web site based application.

Here we go

As you might know already, unlike the Web Forms, there is no Server control or CodeBehind classes available in Razor web sites. All you have is the cshtml files, which contains the plain old html markups with simple Razor expressions @. In Razor, you stay closest to the basic HTML, that gives you the power to customize the front-end functionality to your heart's content. The good news is, even though you don't have the powerful server controls here, you've got powerful built-in Helpers which lets you add complex user interface modules with functionality in the cshtml pages. Razor is simple, and beautiful.

Following are some of the basic Razor things that you should know, in order to be able to start building a real application:

The IsPost property

Like the IsPostBack property in web forms, you can determine whether the current Request is due to a form Post or Get request by checking the IsPost property as follows:

Mixture of HTML and Razor

In Razor, @ is just a replacement of the server side expression <%=%> and <%...%> which are using in aspx web forms. Using the @ symbol doesn't require you to end the expression with something, which greatly simplifies the mixture of HTML markups and server side expressions and improves readability a lot.

Have a look at the following codes:

The basic rule is, you start any server side expression with @, and, you don't need to end it. All of the other programmatic syntax should be there as they should be, like, if you open the curly brace "{", you need to close it "}".

The @Href method

For resolving correct relative paths for resources in HTML, the @Href method is your good friend. The WebPage object (The current object of the page, equivalent to the Page object in WebForms) has this handy method, which could be used as follows to resolve correct relative paths:

Including another page using @RenderPage()

The layout pages contain a @RenderBody()  method, which is replaced by the content of a child page at run-time. Using the layout page thus gives a way to have consistent look of the entire site.

Much like the @RenderBody(), there is another way you can include the output of an another page in an existing page. The @RenderPage(PageName) method allows such facility. For example, a layout page could have a @RenderPage(PageName) to include the output of another page in it. It works much like adding a User Control in an aspx page.

Passing data to Layout page

Passing data from the content page to Layout page is a very basic need. Pages in Razor has a PageData property which is used for this purpose. The following example shows passing Page title from the content page to the Layout page:


A helper is a component that lets you accomplish a task using a single line of code. ASP.NET includes many built-in helpers which are ready to be used in cshtml files, such as the following, which displays data in Grid layout using the built-in WebGrid helper:

There are many built-in helpers which you could use to achieve several necessary functions and features. Some are as follows:

The WebCache helper : Lets you using Caching in cshtml pages as follows:

The FileUpload helper : Lets you upload single or multiple files

The Video helper : Lets you include a Video in the page

The WebMail helper : Lets you send emails

The Bing helper : Lets you add a search functionality with Bing search engine

The LinkShare helper.
The Twitter helper.
The Facebook helper.

These let you add social network functionality in cshtml pages

The WebSecurity helper.
The SimpleMembership helper.
The ReCaptcha helper.

These let you implement user registration and login functionality with Membership
Custom helpers

You also may want to create and use custom helpers in your application and use that helper across the pages for a consistent look and functions. Here is how you can do this:

1. Add the App_Code folder in your web site
2. Create a new .cshtml file inside App_Code folder  and name it Helpers.cshtml.
3. Replace the existing content with the following and save the file:

Once created, you can use the helper as follows:

Further study

Enjoyed Razor? Does it seem interesting? See for more detailed on Razor and keep exploring, Razor is fun.

Welcome ASP.NET Razor View - Part 1

Introduction MVC3 introduces a new View Engine "Razor", which greatly simplifies the creation of view components and improves productivity. Once you have installed MVC3 from, when you create an MVC3 application using Visual Studio 2010, you are going to see a prompt like the following where you need to specify the View Engine (Either Aspx or Razor):

Figure : Specify View Enginge while creating an MVC3 application 

Specifying "Razor" as the view engine results in creating an MVC application based on Razor view engine where the file extensions end up with .cshtml.

Interesting thing is, once you install MVC3, you get a new template in Visual Studio to create an web site based on Razor view engine. Go to File->New->Web Site-> Web Site(Razor) to add a Razor based web site in Visual Studio:

 Figure : Adding an Razor web site in Visual Studio

Doing so would result in adding the following Web Site in Visual Studio, which is based on Razor view engine:

 Figure : Razor web site in Solution explorer

Run the application using Visual Studio and you are likely to see the following output:

Figure : Home page of Razor web site
Hm..seems good. Lets try to understand how this works!


First of all, there is no aspx in Razor, and, no server control, ascx or CodeBehind. All you see is some plain cshtml files all over the web site.

Open the Default.cshtml in Visual Studio (Which results in the above page output in browser) and you will see it contains the following markup:
  Figure : Default.cshtml Markup

As you can see, it contains some plain old basic HTML and some C# scripts written in some new syntax. Yes, you got it right. Razor introduces a new simple way of writing scripts in HTML, which basically could be thought of as a simplified version of writing scripts which we were used to write in Aspx markup.

Conventionally, we used to write scripts or expressions in aspx as follows:

    var date = DateTime.Now;
Current date is : <%=date %>

This expression becomes the following in Razor syntax:

    var date = DateTime.Now;
Current date is : @date

As a result, the markups in Razor view components (cshtml files) becomes a lot cleaner, saves a lot of key strokes for you and lets not forget this syntax is fully supported by Visual Studio intellisence. So, you are getting the best of both worlds.

Understanding _SiteLayout.cshtml

Notice the markup of Default.cshtml and you will see it contains a very minimal amount of codes. Yet it results in a good amount of output in the browser. How is that possible?

Well, the answer is _SiteLayout.cshtml. It acts like what the MasterPage does in a Web Form application and it is used in a Razor web site to define a common layout across a group of pages (cshtml files).

In Razor, if you start a cshtml file name with an underscore (_), user cannot browse the file using URL request (It is prohibited internally). The layout files are files which are to be used as an internal purpose (To define the common layout of the pages) and hence, a layout file name should always start with an underscore (_), like the default layout file _SiteLayout.cshtml.

Open the _SiteLayout.cshtml and you will see the following markups:

Figure : _SiteLayout.cshtml makrup

Notice, its just plain old basic HTML stuff along with some Razor expressions which start with @. Most importantly, notice the @RenderBody() method call in Red box. At run time, the @RenderBody() method call is replaced by the HTML markups defined in the child page (The page which includes this layout page).

So, when the Default.cshtml is browsed, the @RenderBody() method call is replaced by the HTML defined in Default.cshtml, which is nothing but the following simple HTML:

    ASP.NET Web Pages make it easy to build powerful .NET based applications for the web.

Note that, there is no restriction of name with the layout pages except the fact that, it should always start with an underscore(_). Name it as you like and everything should be alright as long as you include the layout page correctly in children pages as follows:

    Layout = "~/_MyLayoutPage.cshtml";

Understanding _AppStart.cshtml

If you need to run some initialization functionality when the application starts, _AppStart.cshtml is the place to do so. Unlike the layout pages, it has a standard name and you cannot rename it other than _AppStart.cshtml.

Open the _AppStart.cshtml and you would see the following markup:
Figure : _AppStart.cshtml markup
Basically, it contains some codes to initialize the database when the application runs.


Expand the Accounts folder and you will see several other cshtml files implemented for User Login, Registration and other user account oriented functionality. All of these utilizes Razor syntax and use the built in helpers in Razor for rendering various UI elements or built in classes for implementing several functionality.

Like a conventional web site, a Razor web site also can have standard folders like the App_Data for holding database and other data sources, or, App_Codes for holding cs files. Similarly, the Razor web site can hold a reference to other class libraries to be able to invoke methods on those libraries to achieve desired functionality. Most importantly, it contains many rich built in "Helpers" which help rendering some common UI output and functionality (Like, Adding a Twitter feed, or, Social network bookmarks) which you would simply love to have!

The next post is going to cover some of the detailed stuff of Razor and I hope you would find it helpful.