ASP.NET MVC 3 Hosting :: Rolling with Razor in MVC v3 Preview

Posted by mbridge on Geeks with Blogs See other posts from Geeks with Blogs or by mbridge
Published on Fri, 04 Feb 2011 02:18:17 GMT Indexed on 2011/02/04 7:26 UTC
Read the original article Hit count: 572

Filed under:
Razor is an alternate view engine for asp.net MVC.  It was introduced in the “WebMatrix” tool and has now been released as part of the asp.net MVC 3 preview 1.  Basically, Razor allows us to replace the clunky <% %> syntax with a much cleaner coding model, which integrates very nicely with HTML.  Additionally, it provides some really nice features for master page type scenarios and you don’t lose access to any of the features you are currently familiar with, such as HTML helper methods.

First, download and install the ASP.NET MVC Preview 1.  You can find this at http://www.microsoft.com/downloads/details.aspx?FamilyID=cb42f741-8fb1-4f43-a5fa-812096f8d1e8&displaylang=en.

Now, follow these steps to create your first asp.net mvc project using Razor:

1. Open Visual Studio 2010
2. Create a new project.  Select File->New->Project (Shift Control N)
3. You will see the list of project types which should look similar to what’s shown:

 

4. Select “ASP.NET MVC 3 Web Application (Razor).”  Set the application name to RazorTest and the path to c:projectsRazorTest for this tutorial. If you select accidently select ASPX, you will end up with the standard asp.net view engine and template, which isn’t what you want.

5. For this tutorial, and ONLY for this tutorial, select “No, do not create a unit test project.”  In general, you should create and use a unit test project.  Code without unit tests is kind of like diet ice cream.  It just isn’t very good.



Now, once we have this done, our brand new project will be created.    In all likelihood, Visual Studio will leave you looking at the “HomeController.cs” class, as shown below:



Immediately, you should notice one difference.  The Index action used to look like:

public ActionResult Index ()
{
ViewData[“Message”] = “Welcome to ASP.Net MVC!”;
Return View();
}


While this will still compile and run just fine, ASP.Net MVC 3 has a much nicer way of doing this:

public ActionResult Index()
{
ViewModel.Message = “Welcome to ASP.Net MVC!”;
Return View();
}


Instead of using ViewData we are using the new ViewModel object, which uses the new dynamic data typing of .Net 4.0 to allow us to express ourselves much more cleanly. 

This isn’t a tutorial on ALL of MVC 3, but the ViewModel concept is one we will need as we dig into Razor.
What comes in the box?
When we create a project using the ASP.Net MVC 3 Template with Razor, we get a standard project setup, just like we did in ASP.NET MVC 2.0 but with some differences.  Instead of seeing “.aspx” view files and “.ascx” files, we see files with the “.cshtml” which is the default razor extension. 

Before we discuss the details of a razor file, one thing to keep in mind is that since this is an extremely early preview, intellisense is not currently enabled with the razor view engine.  This is promised as an updated before the final release. 

Just like with the aspx view engine, the convention of the folder name for a set of views matching the controller name without the word “Controller” still stands.  Similarly, each action in the controller will usually have a corresponding view file in the appropriate view directory.  Remember, in asp.net MVC, convention over configuration is key to successful development!

The initial template organizes views in the following folders, located in the project under Views:

- Account – The default account management views used by the Account controller.  Each file represents a distinct view.
- Home – Views corresponding to the appropriate actions within the home controller.
- Shared – This contains common view objects used by multiple views.  Within here, master pages are stored, as well as partial page views (user controls).  By convention, these partial views are named “_XXXPartial.cshtml” where XXX is the appropriate name, such as _LogonPartial.cshtml.  Additionally, display templates are stored under here.

With this in mind, let us take a look at the index.cshtml file under the home view directory. 

When you open up index.cshtml you should see

1:   @inherits System.Web.Mvc.WebViewPage
2:  @{
3:          View.Title = "Home Page";
4:       LayoutPage = "~/Views/Shared/_Layout.cshtml";
5:   }
6:  <h2>@View.Message</h2>
7:  <p>
8:     To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC    
9:    Website">http://asp.net/mvc</a>.
10:  </p>


So looking through this, we observe the following facts:

Line 1 imports the base page that all views (using Razor) are based on, which is System.Web.Mvc.WebViewPage.  Note that this is different than System.Web.MVC.ViewPage which is used by asp.net MVC 2.0

Also note that instead of the <% %> syntax, we use the very simple ‘@’ sign.  The View Engine contains enough context sensitive logic that it can even distinguish between @ in code and @ in an email.  It’s a very clean markup. 

Line 2 introduces the idea of a code block in razor.  A code block is a scoping mechanism just like it is in a normal C# class.  It is designated by @{… }  and any C# code can be placed in between.  Note that this is all server side code just like it is when using the aspx engine and <% %>. 

Line 3 allows us to set the page title in the client page’s file.  This is a new feature which I’ll talk more about when we get to master pages, but it is another of the nice things razor brings to asp.net mvc development.

Line 4 is where we specify our “master” page, but as you can see, you can place it almost anywhere you want, because you tell it where it is located.  A Layout Page is similar to a master page, but it gains a bit when it comes to flexibility.  Again, we’ll come back to this in a later installment. 

Line 6 and beyond is where we display the contents of our view.  No more using <%: %> intermixed with code.  Instead, we get to use very clean syntax such as @View.Message.  This is a lot easier to read than <%:@View.Message%> especially when intermixed with html.  For example:

<p>
My name is @View.Name and I live at @View.Address
</p>


Compare this to the equivalent using the aspx view engine

<p>
My name is <%:View.Name %> and I live at <%: View.Address %>
</p>

While not an earth shaking simplification, it is easier on the eyes.  As  we explore other features, this clean markup will become more and more valuable. 

© Geeks with Blogs or respective owner