0

Getting started with Razor

A friend recently emailed me and asked me for advice on learning the Razor syntax. I’ve decided to create this blog as a reply in order to benefit anyone else that might have the same question.

Razor is a recent addition to the ASP.NET family and provides a new syntax for defining server side code in an ASP.NET page. Razor works in ASP.NET , ASP.NET MVC and ASP.NET WebPages. In fact Razor was developed for WebPages, but later incorporated into ASP.NET MVC as a first class view engine.

My advice to anyone working with ASP.NET MVC is to learn Razor and use it for new projects. It’s much more concise and you will find yourself building projects slightly faster due to it’s easy and efficient syntax.

In my opinion the two best online resources for learning Razor are the following links:

Before reading any further I would recommend going over these two articles, they are both really good and will give you an understanding of the Razor Syntax.

For the remainder of this post, I’m going to summarize some of the things I have learned about Razor and the caveats you need to watch out for.

Closing Tags Matter

In a razor block, it’s important that your markup is valid and includes all the necessary opening and closing blocks. Razor does not contain a closing code tag so as it result it must analyze the html within a code block and determine when to switch back to code.

Consider the following example:

@if(item.IsEditable){
    <div class=”editable”>
}

else{
    <div>
}

Edit
</div>
The following is an example of a conditional opening tag. Doing this in the aspx view engine would fine without any problems. However, in Razor this will cause an error because the div tag is not closed in the same block scope.

To fix this we should use a ternary operator instead.

<div class=”@(item.IsEditable ? “editable”: “”)“>

    Edit
</div>
As a side note, Razor2, which should is currently available as a release candidate, includes support for conditional classes. For the complete list of what’s new in Razor2 check out these two great blog posts from one of the main developers on Razor.

Layouts are Rendered inside out

Razor doesn’t use Master Pages, instead it has a layout system that allows us to define a layout file (similar to a master page) often called _Layout.cshtml. The layout file can Render a view body or include other views in asp.net mvc.

The order of the rendering is important and is in fact different from the aspx view engine. Unlike aspx, razor renders recursively. Meaning that the inner most view is rendered first, then it bubbles up to the layout page.

This is important when dealing with server variables declared in the layout page. You might be tempted to declare a variable in the layout page and later reference it in the razor view. That won’t work because of the way that Razor works.

Parsing Error

Since Razor relies on valid html in a block, sometimes you can run into a situation where you want to use < or > as actual elements in the page and that might cause an error. For example:

@if (item.IsEditable) {
    <span><<</span>
}
else{
    <span class=”noLink”> N/A </span>
}

The code in the if condition will cause a razor parser error because of the opening braces you can easily fix that, but adding a space between the span tags and the content like so:

@
if (item.IsEditable) {
<span> << </span>
}
else{
<span class=”noLink”> N/A </span>
}

Additional Reading:

Here’s a great blog post on using Razor to perform text templating. This is outside of a standard web context so you wouldn’t use it in a view, but it’s good for using razor to create html on the fly such as in the case of templated emails
http://haacked.com/archive/2011/08/01/text-templating-using-razor-the-easy-way.aspx

Also, as mentioned earlier, Razor is part of ASP.NET WebPages which is a completely different way of building web sites in comparison to asp.net web forms and asp.net mvc. WebPages is a great technology and aimed at a very specific type of website.
http://www.asp.net/web-pages/tutorials/introducing-aspnet-web-pages-2/getting-started

Razor is a great rendering technology and one that I personally enjoy using and will continue to use for a very long time.

Advertisements
0

Knockout JS Presentation

Tonight I’m presenting at the Los Angeles Dot Net user group (LADOTNET). I’ll be covering Knockout JS and how you can use it in an ASP.NET MVC app.  I hope to see you there.

Here are the slides and demos

Slides

Demo Source Code  – Play with the Demos Online

Here’s a few useful links about Knockout JS

Knockout Links

Learn Knockout Js – An excellent interactive tool for learning about Knockout JS

Knockout Me Out – A great blog about Knockout JS

0

SoCal Code Camp Los Angeles 2011

This past weekended I spoke at the 4th annual LA Code Camp. I had an amazing time speaking, listening to some great presentations and interacting with lots of great people. Thanks to everyone that came to my talks!

I would really appreciate feed back on my presentations. So if you attended a talk, please visit my speakerrate page and rate me! 🙂

Here are the Slide Decks and Code Samples from my talks:

0

SLO .NET User Group Talk

Later today I’ll be speaking at the San Luis Obispo .NET User group. I’ll be presenting on Knockout JS, a powerful MVVM library for JavaScript. Knockout makes building interactive rich UI’s a lot of fun! I hope to see you there.

If you do attend, I ask that you please rate my talk so I know how I’m doing 🙂

Here are the slides and demos

Slides

Demo Source Code  – Play with the Demos Online

Here’s a few useful links about Knockout JS

Knockout Links

Learn Knockout Js – An excellent interactive tool for learning about Knockout JS

Knockout Me Out – A great blog about Knockout JS

3

SoCal Code Camp San Diego 2011

This past weekend I attended the SoCal Code Camp in San Diego and I had a blast. I gave 5 talks on mvc related topic and attended several great sessions. It was a fun experience and I truly enjoy going to Code Camp, it’s a great place to learn about new technologies and hang out with other fellow developers and friends.

Here are the slides and code samples from my talks:

0

ASP.NET MVC3 Tools Update – Scaffolding with the Repository Pattern

Today Microsoft released a new add-on for ASP.NET MVC 3. The ASP.NET MVC3 Tools Update does not update any of the dll’s used by an mvc3 project, but adds some great new tooling support. You can read more about in on Phil Haack’s Blog Post regarding this release.

In this post I’m going to show you how to use MvcScaffolding to add a new controller template to enable scaffolding with data access code that uses the Repository Pattern.

One of the new features is built in tooling support for scaffolding. The “Add Controller” Dialog box has been revamped to include a few new options.

 

New Add Controller Tooling

New Add Controller Tooling

 

As you can see there are much more options as compared to before. The scaffolding options are as follows:

  • Template: Allow you to specificy what kind of controller you want to generate. Out of the box you get an empty controller (Just a class with no actions), Controller with actions and views using the Entity Framework code first, and controller with empty read/write actions.
  • Model: This is the object that will be used for scaffolding strongly typed views, CRUD actions and data access.
  • DataContext: By default this is an EF Code First class that inherits from DbContext. You can either select an existing context or have the scaffolding tools create a new one for you.
  • Views: Select between ASPX and Razor. This is pretty much the same as the “Add New View” dialog box.
  • Advanced Options include layout/master page settings and View script settings. Again, stuff that is also in the “Add New View” Dialog.
Add new Controller Templates

Controller Templates

Scaffolding using the “Controller with read/write actions and views, using Entity Framework” is especially cool because it generates a controller, all associated views AND data access code for you. That’s right, all you need to do is create an model class and the scaffolder does the rest. How’s that for a productivity boost? 🙂

To test this I created a simple Product class which is defined as the following:

public class Product{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}

Then I added a new controller with the following options:

Add Controller Product

Product Controller Scaffolding Options

The new tooling support created a new controller, all associated views and the data access code. That’s really cool, but let’s take a look at the controller code.

private ProductContext db = new ProductContext();
 //
// GET: /Product/
 public ViewResult Index()
{
return View(db.Products.ToList());
}

By default the scaffolding tools use the ProductContext object directly in the Controller. Many people don’t like this coupling (myself included) and prefer to use the Repository Pattern. This allows us to abstract away our data access code behind a repository, making it easier to work with and later modify, if need be.

Well the good news is that the add controller dialog is extensible. You can add your own controller templates to enable data access using any technology mechanism you want.

I’m going to show you a way to get a repository option for EntityFramework to show up with very little work. All you need to do is install the MvcScaffolding NuGet Package.

Open the Package Manager Console and enter “Install-Package MvcScaffolding”:
Install MvcScaffolding

Now right click on the controllers folder and select “Add”->”Controller”. We’re going to re-scaffold out our ProductController, associated views and data access code (WARNING: This will overwrite any changes you have made so be careful.)

Now take a look at the templates section and you should see new templates:

MvcScaffolding : Controller using repositories

MvcScaffolding : Controller using repositories

The last option let’s you scaffold out the entire thing and use repositories for data access. Go ahead and click “Add”. Check the checkboxes to allow the scaffolder to override existing items.

We can verify this by looking at our ProductController and we should see the following:

private readonly IProductRepository productRepository;

// If you are using Dependency Injection, you can delete the following constructor
public ProductController() : this(new ProductRepository()) { }
 public ProductController(IProductRepository productRepository) {
this.productRepository = productRepository;
}

//
// GET: /Product/
 public ViewResult Index(){
return View(productRepository.All);
}

Now the controller uses a repository instead of hard coding in the data access code. The repository itself uses EF Code First to do all the data access.

5

Dynamic Header names in the default ASP.NET MVC List Template

In asp.net mvc when you add a view to  correspond with an action method, you have the option of using several pre-defined templates that come with asp.net mvc (Create, Edit, Delete, Details and List.) Depending on the selected template, a particular view is scaffolded for you containing all the markup needed to perform the action. In this post I’m going to discuss the List template and show you how you can get away from the static header that gets generated by default and instead get the name of property from the DisplayName data annotation attribute.

Assuming you have a simple entity object called Products and it looks something like this:

public class Product{
        public int ProductId { get; set; }

        [DisplayName("Product Name")]
        public string Name { get; set; }
    }

Notice how the “Name” property has a display name attribute attached to it. When generating a List template, I expect the column header to be Product Name.

Let’s go ahead and build an action method like so:

        public ActionResult Index(){
            var products = new List(){
                new Product{ProductId=0,Name="Windows Phone 7"}
            };
            return View(products);
        }

It’s a basic action method that creates a fake list of products and sends it to the view. I’m deliberately keeping the action simple and free of any data access code.

Now add a view to for this action method by right clicking on the method and selecting “Add New View”. Add a strongly typed view of type Product and select the List template.

Look at the resulting markup. In particular, look at the first row of the html table (the header row). It should look something like this:

<table>
  <tr>
     <th></th>
     <th>
       Name
     </th>
   </tr>

Instead of getting “Product Name”, the output of the List template was the name of the property. That’s not what we want! So how do we fix this?

It’s actually a pretty easy change. All we have to do is remove the hard-coded static name and instead use the LabelFor html helper.

Change the markup in the view to the following

    @Html.LabelFor(p=>Model.FirstOrDefault().Name)

Since the header row is outside of our foreach loop, we have use the Model property and get the first item in the collection. For a bit of clarification, we are using a lambda that takes in a paramter p. However, we are not using that parameter since in this case we want to reference the first item in our list collection (via the Model property.)

Now open the page in your browser and you’ll see that the header row has the value “Product Name” instead of name since it’s now pulling the name from data annotations instead of just using the property name.

Now that’s great and what we want. But if we have a big website, we’re going to have to make this change for every list View we scaffold out. It would be nice if we can just modify the template so that any new list views automatically use this new syntax. Fortunately we can do that! Scott Hanselman has a great blog post on modifying the default mvc templates.

Follow the instructions on that page and add the Code Templates folder to your asp.net mvc site. After that go into the cshtml folder and open the list.tt file.

Go to line 70 which should be:

<#= property.Name #>

Change that line to include the new LabelFor html helper like so:

@Html.LabelFor(p=>Model.FirstOrDefault().<#= property.Name #>)

Now anytime you create a new list view it will automatically use the LabelFor syntax instead of hard-coding in just the name. I highly recommend you do this before starting a new project as it will make developing the asp.net mvc site much easier.

0

So Cal Dot Net :: ASP.NET MVC3 Best practices

Thanks to everyone that attended my talk at So Cal Dot Net in Buena Park. I had an awesome time and it was a ton of fun.

Here are the files from the presentation:

5

LA C# – ASP.NET MVC 3 Best Practices

Thank you to everyone that attended my asp.net mvc 3 best practices talk at LA C# last night! I had a great time and I look forward to coming back and speaking to you guys about asp.net mvc.

Here are the files from the presentation:

I would also appreciate it if you could provide feedback on my talk via speaker rate. Thanks!