Knockout JS @ The San Francisco .NET Developers User Group

Last night I presented at the San Francisco .NET Developers User Group on Knockout JS with ASP.NET MVC4 and Web API. I had a great time there and I wanted to thank everyone for inviting me to speak to the group.

Here are my slides from the presentation.

Here is the Contact List application we built.(Please note that the demo expects SQL Server express to be running. If you want to use another version of SQL Server, then you just have to add a connection string in Web.Config that matches the name of the data context.)

You can find Knockout JS demos and examples here:

The official Knockout JS website is here:

Additional Resources:
Knock Me Out – This is a great blog by one of the contributors to Knockout JS. Lots of material is covered.

Web API Serialization
Web API Paging and Filtering



ASP.NET MVC– Display the contents of a CSV file in a Telerik Grid

In this article I’m going to show you how to build an ASP.NET MVC web application that will allow you to upload a CSV file and display the results in a Telerik Grid. We’re going to be using two libraries to help us with this task.

Let’s start by downloading and installing the Telerik Extensions, you can either download a free trial or use the open source version of the extensions. Be sure to read the license on the open source version before using it in your applications.

The library add a Visual Studio extension  as well as new project types. This makes it very easy to use the Telerik extensions in a new project.

After downloading and installing the extensions, let’ go ahead and create a new Visual Studio ASP.NET MVC3 Web Application called “CsvToGrid”.


Because we installed the Telerik Extensions for ASP.NET MVC we should see a new Project Template for Telerik MVC Web Application. Let’s select that.


Go through the Telerik Project Configuration Wizard and select all the default options. This will create the project and preconfigure all the necessary settings needed by the extensions. This includes configuration options in the web.config file and referencing JavaScript and css files.

After this let’s go ahead and install LinqToCsv. Right click on the references folder and select “Manage NuGet Packages” then search for “LinqToCsv” and install it.


    We need to define a sample csv file. Let’s add a new file called people.csv to our desktop with the following data:

John, Smith, 35, CA
Mike, Jones, 29, AZ
Susan, Baldwin, 45, CA
Alex, Johnson, 32, WA

As you can see, it’s a simple comma delimited file that represents people and includes their first name, last name , age and state.

We also need a class to represent this data. Let’s add a Person class to our models folder. Add a new class and name file Person.cs The contents of the file should look like this

public class Person{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string State { get; set; }

Now let’s modify the home controllers Index view to include a form an a file upload html control. Replace the contents of the file “Index.cshtml” in the Views/Home folder with the following:


ViewBag.Title = “Home Page”;


@using (Html.BeginForm(“Index”, “Home”, FormMethod.Post, new { enctype = “multipart/form-data” }))


<input type=”file” name=”file” />

<input type=”submit” name=”btnSubmit” value=”Upload!”/>


Now let’s add some code to the controller so that we can save this file to disk. Let’s replace the action methods in HomeController.cs with the following two action methods:

public ActionResult Index(){

return View();



public ActionResult Index(HttpPostedFileBase file){
if (file.ContentLength > 0){

var fileName = Path.GetFileName(file.FileName);

var path = Path.Combine(Server.MapPath(“~/App_Data/”), fileName);


TempData[“file”] = path;


return RedirectToAction(“Grid”);


Here we’ve added a second Index action method that takes in an HttpPostFileBase, this object will hold the reference to the uploaded file. Now it’s important to note that the name of the input parameter (“file” in our case) has to match up with the name of the html control. If the names don’t match up, the input parameter will come through as null.

In the action method we copy the file to the App_Data folder then we save the file path in TempData and redirect to a new Action called Grid.

The Grid action method will be responsible for reading data from the csv file and passing it to the view so that it can be rendered in telerik grid.

Add the following using statements to the top of your HomeController class

using CsvToGrid.Models;
using LINQtoCSV;

Now add the Grid action method to the home controller.

public ActionResult Grid()
     string file = TempData["file"] as string;
     if (file == null)
         return RedirectToAction("Index");

     CsvContext cc = new CsvContext();
     List<Person> people = cc.Read<Person>(file).ToList();

     return View(people);


This action method reads the file path from tempdata, then uses LinqToCSV to convert the data in the file to a collection of “Person”. This data I then returned to the view.

In the view we need to show this data as a Telerik Grid. Let’s define the view as a strongly typed view of type List<Person>. Let’s also add the code for the Telerik Grid. The complete view code should be

@model IEnumerable<CsvToGrid.Models.Person>

    ViewBag.Title = "Grid";



Run the application by pressing alt-F5. On the home screen select the csv file we created earlier and click the upload button. The data within the csv file should now appear as data in your telerik mvc grid.


In part two of this post I’m going to show you how to customize the application so that you deal with csv data that doesn’t include a header row. You can download the complete source code for this demo site here.

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:

    <div class=”editable”>


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”: “”)“>

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 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 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>
<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

Also, as mentioned earlier, Razor is part of ASP.NET WebPages which is a completely different way of building web sites in comparison to web forms and mvc. WebPages is a great technology and aimed at a very specific type of website.

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

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:

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.

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

In 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 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:


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


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 mvc site. After that go into the cshtml folder and open the 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 mvc site much easier.

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:

LA C# – ASP.NET MVC 3 Best Practices

Thank you to everyone that attended my 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 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!

SoCal Code Camp Fullerton 2011

This weekend I attended and spoke at Code Camp Fullerton 2011. As always I had an amazing time. It’s always fun to meet and interact with other fellow developers. I went to a few really good sessions by some great presenters. I was also able to give a few talks myself on one of my favorite topics, ASP.NET MVC. Thanks to everyone that attended. I hope I was able to share my knowledge with you and if you have any further questions, feel free to contact me. I’m looking forward to Code Camp San Diego in a few months!

Here are the slides and code samples.

LA So Cal Code Camp

Last weekend I fortunate enough to attend SoCal Code Camp Los Angeles. It was an awesome event and lots of fun.Thanks to all who attended my presentations. I would appreciate any feedback you might have. Please leave comments at

Here are the slides and code samples.

    • Getting Started with ASP.NET MVC
      Download the Powerpoint slides.
      Download the
      Sample Project
    • ASP.NET MVC 2 Best Practices
    • Download the Powerpoint slides.
      Download the ToDoList.Bad projectThis is an example of poorly created mvc application. Some of the problems with it:

      • Data Access Code (linq 2 sql in this case) is placed in the controller instead of a business layer.
      • Action method extracts value from Request.Form instead of action method input parameters.
      • Validation is in the controller and is repeated across multiple actions via copy paste.
      • Controller creates html as a string. (Violates the mvc pattern)
      • PRG (Post-Redirect-Get) pattern not used. After a post, a user clicking refresh can cause data to be modified again!
      • Code Duplication via copy paste. Violates DRY (don’t repeat yourself) principle.

      Download the ToDoList project
      Here’s the same project but built using a good separation of concerns and unit testing.

    • Download the Sample Project
      Download the Telerik Sample
      For instructions on setting up a new project with the Telerik extensions for mvc, see this post.

    • What’s New in ASP.NET MVC3
      Download the Powerpoint slides.
    • Download the Sample Project