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.