You are currently browsing the Bit Candies posts tagged: backbone


ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part IV

Welcome back! This post is the last part of our ground-up tutorial. Our aim is to show the feasibility of interfacing the famed Backbone Todo demo with a REST ASP.NET backend.
You can find previous parts at:

Let’s have a brief recap: in the first part we only set up our dev environment with a database and a Visual Studio solution, in the second we created the Model on top of Entity Framework 4 and in the last we dealt with the Controller outlining all the REST actions. You can find up-to-date code for this tutorial at this link.

Today we will complete our recipe about our well-known ASP.NET MVC3 application, working with the View, garnishing it with Backbone.js. We will have an overview about Backbone, then analyze a bit the structure of the Todo demo and in the end we will easily brush our application with Backbone’s Todo files.

Backbone.js

Backbone.js is a Javascript framework based on the handy MVC architecture. The main point of choosing Backbone for your dynamic applications is the structuring you gain in the process. It gives you a score of best practises to logically divide your everyday’s work as opposed to simply write messy javascript code tied up with DOM elements. We call it an MVC framework for the View.

In Backbone a Model can be pretty much everything, but at its core it is the interactive data of your application, together with the methods to modify it. Collections are an handy addictions: they handle model additions, changes and deletion. If we look at the Todo demo js file we can spot a Todo model

  window.Todo = Backbone.Model.extend({

  // ... a couple of functions ...

  });

and a Todo Collection. Pay attention to the localStorage line, we will change it later.

  window.TodoList = Backbone.Collection.extend({

    model: Todo,

    localStorage: new Store("todos"),

    // ... some other functions ...

  });

The object named View in Backbone can be a bit confusing, as it can be considered the real Controller of the application: it reacts to user interactions and dispatches events. It is bound to a DOM element and in charge of a part of the UI, but does not deal directly with HTML elements.

  window.TodoView = Backbone.View.extend({

    tagName:  "li",

    template: _.template($('#item-template').html()),

    events: {
      "click .check"              : "toggleDone",
      "dblclick div.todo-text"    : "edit",
      "click span.todo-destroy"   : "clear",
      "keypress .todo-input"      : "updateOnEnter"
    },

    initialize: function() {
      this.model.bind('change', this.render, this);
      this.model.bind('destroy', this.remove, this);
    },

    render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
      ...
      return this;
    },

    // ... more functions ...

  });

To draw the page Backbone relies on a templating engine, which is the real View in a traditional MVC sense. Backbone is agnostic with respect to the HTML template: you are in charge of the choice: we usually like Mustache.js.

Underscore.js is the only dependency for Backbone and in fact this demo dodges the use of other template engines and instead relies on it, as you may notice looking at the the _.template function attached to the template property in the previuos View of the Todo model

Here, instead, you find the template for that view with id item-template

   [...]

   <script type="text/template" id="item-template">
      <div class="todo <%= done ? 'done' : '' %>">
        <div class="display">
          <input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
          <div class="todo-text"></div>
          <span class="todo-destroy"></span>
        </div>
        <div class="edit">
          <input class="todo-input" type="text" value="" />
        </div>
      </div>
    </script>

   [...]

As a convention, AppView is a special View that is the entry point of a Backbone application and it’s triggered by a “jQuery.ready” function. In this demo it initializes the Todo collection fetching the models, sets the list up and binds the proper events to their delegates.

$(function(){

  [...]

  // Our overall **AppView** is the top-level piece of UI.
  window.AppView = Backbone.View.extend({
    [...]
  });

  // Finally, we kick things off by creating the **App**.
  window.App = new AppView;
})();

Good! Now you have at least the grip of the structure of a very simple Backbone app. Let’s get our hands dirty!

Cleaning up your project

Before dealing with the Todo demo files we will clean our VS solution to remove any trace of the standard bluish template. Delete every file into the “Content” directory (both the theme folder and the css file). Then delete the “AccountController” in the “Controllers” folder, then the “Views/Account” folder together with “Views/Shared/_Layout.cshtml”, “Views/Shared/_LogOnPartial.cshtml” and “Views/_ViewStart.cshtml”. Finally delete every js file in the “Scripts” folder except jquery-1.4.4*. You can find in this archive every file you need (png, css, html, js), directly from the Todo demo (thanks to Jérôme for the permission to redistribute them!). You could just unpack the archive in the main solution folder and then we will work on these files; replace if needed.

Now a bit of (tedious but necessary) housekeeping… In the solution explorer in VS (Right click on the “Scripts” folder) Add –> Existing Item and add “Scripts/underscore-1.1.6.js”, “Scripts/backbone.js” and “Scripts/todos.js”. (Right click on the “Content” folder) Add -> Existing Item and add “Content/destroy.png” and “Content/todo.css”.

Let’s now fix the paths. Open “Content/Home/Index.cshtml” and replace the existing head section with this Razor empowered snippet of code

  <head>
    <title>Backbone Demo: Todos</title>
    <link href="@Url.Content("~/Content/todos.css")" media="all" rel="stylesheet" type="text/css"/>
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")"></script>
    <script src="@Url.Content("~/Scripts/underscore-1.1.6.js")"></script>
    <script src="@Url.Content("~/Scripts/backbone.js")"></script>
    <script src="@Url.Content("~/Scripts/todos.js")"></script>
  </head>

Changing Persistence

As we have noted before, the demo overrides “Backbone.sync” (the facility to load/save models to the server), relying on localStorage for persistence. Of course, this is quite useful for fast prototyping the application, but it is in contrast with our requirements. We need in fact to store our data using the ASP.NET/SQL backend. We have already deleted the reference to the Backbone-localstorage library, but the application still tries to use this persistence module. Adding support for REST-based persistence is as easy as changing the localStorage line we marked before, with the url to the REST APIs. Open “Scripts/todos.js” and change

localStorage: new Store("todos"),

with

//  Use REST url instead of localStorage facility
url: function () {
    return "api/Todos" + (this.get('id') ? '?todoId=' + this.get('id') : '')
},

And voilà! Our dish is ready at last! You can now run the project and try the working demo. If you like these tutorials show some support in the comments ;)

Final version of the application: Download

Extension

Backbone’s documentation suggests that

when your app first loads, it’s common to have a set of initial models that you know you’re going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page. You can then use reset to populate your collections with the initial data.

We will change our example to add model prefetching capability.

Let’s write a simple extension method as helper to deal with JSON serialization.

(Right click on “Todo” Project in the Solution Explorer) Add –> New Folder. Name it “Helpers”. Then (Right click on “Helpers” folder) Add –> New Item –> Visual C# –> Web –> Class. Name it “JsonHelper.cs” and click Add. The code for the helper is here

using System.Web.Script.Serialization;

namespace Todo.Helpers
{
    public static class JsonHelper
    {
        /// <summary>
        /// Converts an object to a JSON string.
        /// </summary>
        /// <param name="obj">The object to serialize.</param>
        /// <returns>The serialized JSON string.</returns>
        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }
    }
}

Then comment the

    Todos.fetch();

line, way down in “todos.js”. In the end, the “Index.cshtml” needs a couple of edits. At the top of the file add

@model IEnumerable<Todo.ViewModels.TodoViewModel>
@using Todo.Helpers

and before the “templates” section add

    <!-- Prefetch -->
    <script type="text/javascript">
        $(function () {
            Todos.reset(Todos.parse(@Html.Raw(Model.ToJson())));
        });
    </script>

Prefetching enabled! Hope you enjoyed the effort ;)

ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part III

Took a while for our mix to stand but now it is time to go back to work on it! We still look forward to sample the Backbone Todo demo with an ASP.NET REST aftertaste. As you can see in title this is the third part of our tutorial. In the last two posts, we already added in the mixing bowl: c# and asp.net mvc3; today it’ll be the proper time to add a bit of REST here and there. If you are keen on doing the recipe yourself, you can start with the first part here: ASP.NET MVC3 Tutorial with Backbone.js – Part I. Otherwise if you are in a hurry you can start with our prepackaged mix of the first two parts: ASP.NET MVC3 Tutorial with Backbone.js – Part II.

Last time we dealt with Models and ViewModels, today we will speak about the core on the application: the REST Controller!

Controller

First of all, get rid of the About Controller: we won’t need it. We will work on the sample Home controller. In this section you will find the shortest implementation possible of the 4 REST verbs using JSON as transfer media, later we will adjust routing to fit in the new architecture.

Open your “HomeController” in the “Controller” folder. Trash everything: don’t worry we will replace the code straight after.

The following snippet is the REST controller of our application.

using System.Collections.Generic;
using System.Web.Mvc;
using Todo.DAL;
using Todo.ViewModels;

namespace Todo.Controllers
{
    public class HomeController : Controller
    {
        private IRepository<Todo> repository = null;

        public HomeController()
        {
            repository = new TodoRepository();
        }

        public HomeController(IRepository<Todo> repository)
        {
            this.repository = repository;
        }

        [HttpGet]
        public ActionResult Get()
        {
            var todos = repository.FindAll();
            var list = new List<TodoViewModel>();
            foreach (Todo t in todos)
                list.Add(new TodoViewModel(t));

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Post(TodoViewModel newTodo)
        {
            Todo todo = new Todo();
            UpdateModel(todo, new[] { "Text", "Done", "Order" });
            ValidateModel(todo);
            repository.Add(todo);
            repository.Save();
            return Json(new TodoViewModel(todo));
        }

        [HttpPut]
        public ActionResult Put(int id, TodoViewModel newTodo)
        {
            Todo todo = repository.Get(id);
            UpdateModel(todo, new[] { "Text", "Done", "Order" });
            ValidateModel(todo);
            repository.Save();
            return Json(new TodoViewModel(todo));
        }

        [HttpDelete]
        public ActionResult Delete(int id)
        {
            Todo todo = repository.Get(id);
            if (todo != null)
            {
                repository.Delete(todo);
                repository.Save();
            }
            return Json(new { });
        }

        public ActionResult Index()
        {
            var todos = repository.FindAll();

            var list = new List<TodoViewModel>();
            foreach (Todo t in todos)
                list.Add(new TodoViewModel(t));

            return View(list);
        }
    }
}

You may recognize at this point the familiar Index action and the four REST actions: GET, POST, PUT and DELETE. As you may notice we take advantage of the Repository infrastructure and ViewModels coded last time and, as said, we return JSON strings to the invoking client. We are quite proud of the brevity of the code: that’s really pretty much everything you need. You could probably write more code to register the routes than to handle the controller actions themselves!

Routes

Now we just have to setup the routes to handle invocation. Our URLs will start in the format “/api/Todos” like:

  • /api/Todos for GET (all)
  • /api/Todos/{id} for GET (one)
  • /api/Todos for POST
  • /api/Todos/{id} for PUT
  • /api/Todos/{id} for DELETE

Open your “Global.asax”. We will rewrite the “RegisterRoutes” method. Here’s the code:

public static void RegisterRoutes(RouteCollection routes)
       {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            var url = "api/Todos";

            routes.MapRoute(
                "Todo_GET",
                url,
                new { controller = "Home", action = "Get", area = "" },
                new { httpMethod = new HttpMethodConstraint("GET") }
            );

            routes.MapRoute(
                "Todo_GET_ONE",
                url + "/{id}",
                new { controller = "Home", action = "GetOne" },
                new { httpMethod = new HttpMethodConstraint("GET") }
            );

            routes.MapRoute(
                "Todo_POST",
                url,
                new { controller = "Home", action = "Post" },
                new { httpMethod = new HttpMethodConstraint("POST") }
            );

            routes.MapRoute(
                "Todo_PUT",
                url + "/{id}",
                new { controller = "Home", action = "Put" },
                new { httpMethod = new HttpMethodConstraint("PUT") }
            );

            routes.MapRoute(
                "Todo_DELETE",
                url + "/{id}",
                new { controller = "Home", action = "Delete" },
                new { httpMethod = new HttpMethodConstraint("DELETE") }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

…and today’s work is done! You now have a working REST application. Next time we will garnish it adapting Backbone demo to our backend.

See you soon!

ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part II

Last week we blogged the first part of a four-part recipe for an ASP.NET MVC3 RESTful application with Backbone.js. For the few of you who may have missed the post, it is a tutorial to get the popular Backbone’s Todo demo working with an ASP.NET MVC3 backend.
We started kneading our mix, setting up a Visual Studio 2010 project and adding to it Entity Framework 4 and generating the database. If you followed the first part, just keep reading, otherwise you can get back on track downloading the ASP.NET MVC3 Tutorial with Backbone.js – Part I.

This article and the following two will deal with the 3 parts of our Model-View-Controller web application respectively. Today we start with the core: it’s Model day!

The Model Layer

Given that we adopted ADO.NET as ORM framework with a “Model-First” approach, we don’t need to explicitly create a Todo class as Model. We now find ourselves quite embarassed: we have to admit it, we lied! We defined our Model last time, thanks to the designer. If you don’t believe us, open in the editor TodoEntities.Designer.cs, found under TodoEntities.edmx.
Open the Entities Context et voilà, you will find there your Model class already defined for you. In this project it is not required, but you may extend this class using C#’s partial classes.

Model layer already done and done? Of couse not! This was just the easy part. We still have to create a very simple ViewModel and a Database Abstraction Layer.

The ViewModel

Yes, we learnt our lesson: model, view and controller interact among them as described in the MVC pattern, but we find healtier to use ViewModels for the binding between View and Model. In this project, it is probably quite silly due to the triviality of the Todo model, but we believe it a best-practice to enforce nonetheless.

(Right click on “Todo” Project in the Solution Explorer) Add –> New Folder. Name it “ViewModels”. Then (Right click on “ViewModels” folder) Add –> New Item –> Visual C# –> Web –> Class. Name it “TodoViewModel” and click Add.

New Todo ViewModel

As we said the code for the ViewModel is pretty trivial. We advise to only pay attention to the word capitalization: we use lowercase words here to accomodate the Todo demo’s capitalization.

using System;

namespace Todo.ViewModels
{
    public class TodoViewModel
    {
        public int id { get; set; }
        public string text { get; set; }
        public bool done { get; set; }
        public int order { get; set; }

        public TodoViewModel() { }

        public TodoViewModel(Todo t)
        {
            this.id = t.Id;
            this.text = t.Text;
            this.done = t.Done;
            this.order = t.Order;
        }
    }
}

Easy enough?

Database Abstraction Layer

Once again speaking of best practises, we will avoid directly calling the ORM’s ObjectContext from the Controller. Instead to abstract the database access, we will add a thin layer, unusually named Database Abstraction Layer (DAL). The layer will be loosely based on Fowler’s Repository Pattern. This choice promotes code reuse, testability, centralized access to your database and… well! It tastes nice too!

Let’s create first a DAL folder in the project, (Right click on “Todo” Project in the Solution Explorer) Add –> New Folder. Name it “DAL”. At this point we first write a IRepository interface and then implement it in a TodoRepository.

The Interface

(Right click on “DAL” folder) Add –> New Item –> Visual C# –> Code –> Interface. Name it “IRepository” and click Add.

New IRepository Interface

Below you can find the clean interface code

using System;
using System.Linq;
using System.Collections.Generic;

namespace Todo.DAL
{
    public interface IRepository<T>
    {
        IQueryable<T> FindAll();
        T Get(int id);
        void Save();
        T Add(T t);
        void Delete(T t);
    }
}

The Repository

Next we will implement the IRepository interface in a TodoRepository.
(Right click on “DAL” folder) Add –> New Item –> Visual C# –> Web –> Class. Name it “TodoRepository” and click Add.

New TodoRepository

Here’s the code

using System;
using System.Collections.Generic;
using System.Linq;

namespace Todo.DAL
{
    public class TodoRepository : IRepository<Todo>
    {
        private TodoEntitiesContainer db = new TodoEntitiesContainer();

        public IQueryable<Todo> FindAll()
        {
            return db.TodoSet;
        }

        public Todo Get(int id)
        {
            return db.TodoSet.FirstOrDefault(c => c.Id == id);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        public Todo Add(Todo todo)
        {
            db.TodoSet.AddObject(todo);
            return todo;
        }

        public void Delete(Todo todo)
        {
            db.TodoSet.DeleteObject(todo);
        }
    }
}

If some of you are disappointed by the results, let’s summarize what have we accomplished:

  • discovered the Todo model class, already created by the Entity Framework Designer;
  • provided a separation between the Model and the View thanks to the use of a TodoViewModel;
  • abstracted the database and restricted its access to only a subset of methods through the IRepository interface;
  • implemented the interface with a specialized TodoRepository class;
  • built a self-contained Model layer, which could be moved in a different VS project, should the need arise

Not so bad, uh? See you for the next part: the Controller!

ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part I

Today’s post is the beginning of a sweet candy recipe for the developers out there. We found out that in the last half-year the community produced a ton of tutorials and how-tos targeting ASP.NET MVC3, but only a few of them with RESTful applications in mind. For this reason, our task today is set on cooking an ASP.NET MVC3 RESTful application.
We will build the application from scratch in 4 phases, each focusing on small tasks. We had trouble finding established best-practices for the process: anyway we will strive to write nice looking code and stay simple in the meanwhile.

We hear already the back row students grumbling noisily: developing a RESTful application is an interesting academical exercise, but what for? For this reason late in the cooking, we will spice our candy with a pleasant aftertaste of Backbone.js. In fact, our project will be a re-visitation of the popular Backbone’s Todo demo for ASP.NET MVC3.

Our recipe will be divided in four parts, roughly related to MVC three-tiered architecture:

  1. Project setup
  2. Model
  3. Controller logic
  4. Presentation layer & integration with Backbone

Having laid out our plan, let’s get our hands dirty with the first step!
This first part is pretty much standard operating procedure for most of you, but it’s the ground upon which we will build the next ones.

Requirements

We tested our project with

  • Visual Studio 2010 Professional
  • .NET Framework 4
  • ASP.NET MVC3
  • SQL Server 2008 Developer Edition

It may work even with scaled down versions of VS or SQL Server. Please note, anyway, that you should NOT employ SQL Server Compact Edition: this will give you many headaches and in the end it may not work at all ;)

Project Setup

Start your Visual Studo 2010 and choose
File –> New –> Project –> Visual C# –> Web –> ASP.NET MVC3 Web Application.
Below type in “Todo” as project name.

New Project

We will start with a basic scaffold in place, so in the next form select Internet Application template and Razor as view engine. You can omit unit test project creation.

Template

You can now run your project: if everything is ok you’ll be greeted by the “Welcome to ASP.NET MVC!” white-blue home page.

Data Layer

The first real stage is to setup the data layer of our project. We opted for Entity Framework 4 as ORM. We ruled out Code-First and selected a Model-First approach. With it, you can design a data layer from ground up: you draw within the Designer tool the conceptual model and then a handy wizard derives for you the database generation script (SSDL) and the correct mapping (MSL).

To do this
(Right click on Todo Project) Add –> New Item –> Visual C# –> Data –> ADO.NET Entity Data Model. Name it “TodoEntities”. Click Add and then select Empty Model.

Ado.NET Entity

At this point you should see in your Solution Explorer an .edmx file and be presented with an empty model in the designer.(Single click in the empty area) and then on the property side panel change Pluralize New Objects to true.

Now let’s add an entity for our Todo model.

Please right click in the Designer area and Add New –> Entity. Name it “Todo”. Leave alone the other fields and press Ok.

New Entity

You have just added your first entity to the model. We will now need to augment the model’s properties.
(Right click on the Todo model) Add New –> Scalar Property . Name it “Order” (from now on pay attention to word capitalization).
On the Properties panel, change the type for the property to Int32.

New Property

Do the same for two more properties: “Done” (Boolean) and Text (String). Now save and you will have a Todo Entity with 3 properties defined by you and a primary key, Id. It should look like this

Todo Conceptual Model

Good! Let our entities bake in the oven and in the meanwhile create the database. First we need a connection to our database server.
(Right click on the designer area) Generate Database From Model. In the wizard choose New Connection and in the Data Source choose Microsoft SQL Server. Then fill in “LOCALHOST” as Server Name (if you have the database server on the development machine, the correct address otherwise) and “Todo” as Database Name like this

New Database Connection

When you click Ok you will be asked to create the database, because it does not yet exist. Answer yes and let VS create it for you. In case it is disabled, tick the check-box to save the credentials in your web.config. A couple of Next and Finish should bring you to end of the DDL script generation process. At this point you will be presented in VS with the script to generate your db. If you take a quick look at it, you should note that it’s simple SQL.

The last step of this section is the actual database creation. With the script still opened, select Execute SQL from the toolbar. Simply click Connect on the Connect to Database Engine dialog. Please note that in any authentication case you choose, you should have a credential with the proper permissions to create a database.

If your query will complete successfully, congratulations! You are ready for the next part of the recipe: Model creation.

Stay tuned and don’t let our mix get burned in the meanwhile!