Friday, September 02, 2011

ASP.NET MVC3 - Razor view engine

Recently I've started working with ASP.NET MVC3 - I had some break from working with .NET. My first impression when looking at new project was - hey where are controls known from aspx pages? I've used to work with them some time later, but now files have strange .cshtml extensions?
ASP.NET MVC3 come with new default viewing engine - Razor - a very nice engine I must say. Its syntax is very easy to remember and generally is very intuitive and lightweight.
Some examples:
Hello @ViewBag.UserName
As you see there is nothing such as closing tag. We only write '@' and that's all. Now have a look at the for loop:
@foreach (var element in Model)
Mixing HTML and Razor is very unobtrusive. If we want to do some code inside view (bad practice) we can just type:

   string text="Hello";
   text+=" World";
Our layout page can look as follows:
        <title>Title of our page</title>
  <div>Common part of all pages</div>

Writing own view helpers is also very easy:

@helper MyHelper(string text)
Razor have some small disadvantages - we can't use big collection of prepared controls - but we can have ASPX and Razor views in one project - so there's no problem at all. When using Razor we now have better control over generated HTML. Better looking code, and views - Razor it's really worth using. As I said earlier Razor doesn't allow us to use .NET controls in it, we also can't use designer view in creating views - but we have something in exchange - the very good set of prepared helpers hidden it @Html.
We have helpers for creating forms, form inputs, links to another actions, to render another views or actions inside current view. For example this is the code responsible of viewing form input and validation message for it:
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)  

Whe talking about Razor I can't ommit the @model keyword - which is very helpful. We can create strongly typed views - so view can only display one model class. So in action we write:
return View(modelToRender);
And in the beginning of the view we put something like this
@model OurNamespace.TypeOfOurClassToRender
From now on this view takes only instances of this class to render. To use this instance inside a view we just type:
Take a good look, because there a difference in these keywords - one starts with upper case "M", and it's very important difference.
So I can say that Razor is very kind to work with. If you are not sure about using Razor in your projects don't hesitate to try it - you're going to love it for its simplicity and ease of use.