Introduction to Single Page Applications in ASP.NET MVC

Introduction

ASP.NET MVC 4 Beta introduced Single Page Applications (SPA), web applications that provide rich functionality to a web page through client side scripting. As of this writing support is limited, but it does provide a basic framework for building data driven web pages using popular JavaScript libraries. This article discusses the SPA project template and parts of a typical SPA application.

What are Single Page Applications (SPA)?

Normally a web application is a collection of web pages, each doing a specific task. For example, consider a web application that does CRUD operations (Create, Read, Update and Delete) on data. A common practice is to create different web pages for operations such as showing a list of existing records, adding a new record, updating an existing record and deleting a record. A trend becoming increasingly popular is to have a single web page perform all of these operations. Such an application is called Single Page Application or SPA. So, in this example instead of developing four separate web pages you develop just one web page. At runtime, depending on the operation selected by a user, the web page renders an appropriate user interface. Such an application heavily relies on client side JavaScript libraries.

It should be noted that SPA is a general concept and ASP.NET MVC 4 has decided to offer some basic infrastructure to the developers to put this concept into practice. ASP.NET MVC 4 provides a project template that creates a basic yet functional SPA application. You can then customize the application to add more functionality. In the discussion that follows you will learn SPA with respect to ASP.NET MVC 4.

Parts of SPA

A Single Page Application consists of several pieces that fit together to provide the overall functionality of the application. A typical SPA consists of the following pieces:

  • Data Model : This is a server side piece that represents your data (often mapping database tables as .NET objects).
  • Data Service : Data service provides operations for database access (typically CRUD operations). This is also a service side piece and uses Entity Framework Code First approach.
  • ViewModel : View Model refers to your data and UI level operations that you wish to perform on the data. You can think of View Model as a wrapper over your model data that adds UI level operations to it. For more details of ViewModel read Implementing MVVM Pattern in Web Applications Using Knockout. A ViewModel resides as a client side piece of code.
  • Views : Views display your data to the user and also contain associated JavaScript. The default SPA project template uses Razor views.
  • Database: SPA uses Entity Framework Code First approach for database operations. The default project template creates a database in the local installation of SQL Server Express.

The following sections discuss all these parts from the default SPA project template in detail.

Creating a New Project Based on SPA Template

Installing ASP.NET MVC 4 adds a new project template in Visual Studio 2010. To create a new SPA you should create an ASP.NET MVC4 Web Application project based on this template.

New ASP.Net MVC 4 Project
New ASP.Net MVC 4 Project

The default project created using the SPA project template contains data models, views and client script files for performing CRUD operations of a sample "To Do" application. SPA extensively uses two JavaScript libraries, namely Knockout and Upshot. The following figure shows these libraries added in the Solution Explorer.

Knockout and Upshot Libraries
Knockout and Upshot Libraries

Data Model

The sample application created by the default SPA project template deals with "To Do" items, i.e. tasks. A task is represented by a data model class - TodoItem. The TodoItem class resides in the Models folder and looks like this:

public class TodoItem
{
    public int TodoItemId { get; set; }
    [Required]
    public string Title { get; set; }
    public bool IsDone { get; set; }
}

As you can see the TodoItem is a simple class with three properties, viz. TodoItemId, Title and IsDone. The Title property is a required property as indicated by Data Annotation Attribute [Required].

To deal with the application data you need to create a DbContext and a DbDataController. This is done for you when you add a new controller to the project specifying the SPA controller template. Right click on the Controllers folder and select Add > Controller. In the Add Controller dialog specify details as shown below:

Add Controller
Add Controller

Specify the controller name as TodoController. Select scaffolding template of "Single Page Application with read/write actions and views, using Entity Framework". In the Model class drop-down select TodoItem class. In the Data context class drop-down click "New data context" and specify a name for the DbContext class. Once you click on the Add button the following files will be created for you:

  • TodoController.cs (Controllers folder)
  • SPADefaultDemoController.cs (Controllers folder)
  • SPADefaultDemoController.TodoItem.cs (Controllers folder)
  • SPADefaultDemoContext.cs (Models folder)
  • Index.cshtml and associated partial views (Views folder)

Out of these classes the DbContext class (SPADefaultDemoContext) looks like this:

public class SPADefaultDemoContext : DbContext
{
    public DbSet<TodoItem> TodoItems { get; set; }
}

As you can see the SPADefaultDemoContext class inherits from DbContext base class and contains a DbSet of TodoItem.

Data Service

The job of performing CRUD operations is handled by the SPADefaultDemoController (the data service) class. This class is shown below:

public partial class SPADefaultDemoController : 
               DbDataController<SPADefaultDemo.Models.SPADefaultDemoContext>
{
    public IQueryable<SPADefaultDemo.Models.TodoItem> GetTodoItems() {
        return DbContext.TodoItems.OrderBy(t => t.TodoItemId);
    }
 
    public void InsertTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        InsertEntity(entity);
    }
 
    public void UpdateTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        UpdateEntity(entity);
    }
 
    public void DeleteTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        DeleteEntity(entity);
    }
}

As you can see the SPADefaultDemoController class inherits from DbDataController base class and includes methods for selecting, inserting, updating and deleting TodoItem records to the database. The data service is called from the client side JavaScript code as you will see later.

ViewModel

The ViewModel class for the TodoItem data model is created automatically for you and is placed in the Scripts folder.

TodoItemsViewModel.js
TodoItemsViewModel.js

As you can see TodoItemsViewModel.js file is placed in the Scripts folder. This ViewModel is developed using Knockout and a part of it is shown below:

// TodoItem class
var entityType = "TodoItem:#SPADefaultDemo.Models";
MyApp.TodoItem = function (data) {
    var self = this;
    // Underlying data
    self.TodoItemId = ko.observable(data.TodoItemId);
    self.Title = ko.observable(data.Title);
    self.IsDone = ko.observable(data.IsDone);
    upshot.addEntityProperties(self, entityType);
}
...

As you can see the TodoItem ViewModel class contains the same properties as the server side data model. These properties are observable properties as indicated by ko.observable() syntax. Knockout synchronizes the data between views and ViewModel. The communication between the ViewModel and the server side data happens through Upshot.js.

View

The Index.cshtml file represents the main view of the application. Three partial views are also created viz. _Grid, _Editor and _Paging that provide the user interface for list, insert/update and paging respectively. Depending on the operation selected by the user the appropriate partial view is rendered. The following markup shows a fragment from the Index.cshtml.

@{
    ViewBag.Title = "TodoItems";
    Layout = "~/Views/Shared/_SpaLayout.cshtml";
}
 
<div data-bind="visible: editingTodoItem">
    @Html.Partial("_Editor")
</div>
 
<div data-bind="visible: !editingTodoItem()">
    @Html.Partial("_Grid")
</div>
 
<div class="message-info message-success" data-bind="flash: { text: successMessage, duration: 5000 }"></div>
<div class="message-info message-error" data-bind="flash: { text: errorMessage, duration: 20000 }"></div>
 
<script type="text/javascript" src="@Url.Content("~/Scripts/TodoItemsViewModel.js")"></script>
<script type="text/javascript">
    $(function () {
        upshot.metadata(@(Html.Metadata<SPADefaultDemo.Controllers.SPADefaultDemoController>()));
 
        var viewModel = new MyApp.TodoItemsViewModel({
            serviceUrl: "@Url.Content("~/api/SPADefaultDemo")"
        });
        ko.applyBindings(viewModel);
    });
</script>

Notice that data service URL is specified as ~/api/SPADefaultDemo. The Html.Metadata() method provides the metadata of the types to the Upshot. The binding between View and ViewModel is provided by the applyBindings() method of Knockout.

If you run the application and navigate to http://localhost:1275/todo (change the port no. as per your setup) you will see something similar to the following figure.

TodoItems
TodoItems

You can click on the "Create TodoItem" button to add a few records. You can then modify or delete them. The following figure shows the view in edit mode.

Edit TodoItem
Edit TodoItem

Database

At this stage the sample "To do" application is able to store and retrieve the data but you might be wondering where the actual data is. Since SPA uses Code First approach to database operations, the database is automatically created for you when you run the application for the first time. The subsequent runs use the previously created database. Have a look at the following figure that shows a sample database generated under local installation of SQL Express.

Sample database generated under local installation of SQL Express
Sample database generated under local installation of SQL Express

As you can see, by default the database name is the same as the fully qualified name of the DbContext class. Inside there is a TodoItems table that stores the application data. To know about Entity Framework Code First read Introduction to Entity Framework Code First.

Summary

Single Page Applications heavily use client side scripting to provide rich functionality to the end user. Instead of creating multiple web pages to perform a set of operations SPA uses a single web page to perform the same tasks. ASP.NET MVC 4 provides a basic framework for building SPA applications. This article examined the project created by the default template. You can modify this code as per your requirements.

About the Author:

Bipin Joshi is a blogger and author who writes about apparently unrelated topics - Yoga & technology! A former Software Consultant and Trainer by profession, Bipin is programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. Having embraced Yoga way of life he now writes about Yoga, life and technology on his website. He can also be reached there.



Related Articles

Downloads

Comments

  • wheloltabotly PumeSonee Phobereurce 9165667

    Posted by TizefaTaNaday on 07/06/2013 02:20am

    DyelayLeavied www.officeoa.cn/include/burberrypurses-nordstrom.html detadvenuelak www.zccd.cn/admins/gucci-large-shoulder-bag.html pooleagophy

    Reply
  • wheloltabotly PumeSonee Phobereurce 5659076

    Posted by TizefaTaNaday on 06/10/2013 03:09pm

    Tapstatuege jordan11anniversarysale.holidaygiving.org edildilditS airjordan1retrocheap.holidaygiving.org fraundcaf

    Reply
  • GHD realmente ocupan una gran cuota de mercado en la industria del cuidado del cabello

    Posted by wanzilucky on 06/05/2013 07:29pm

    [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]baratas ghd outlet[/url] GHD (buen día del pelo) no es sólo el nombre detrás de España y número uno del mundo el pelo de venta de productos alisadores, la plancha de cerámica del pelo GHD, pero GHD España también presta su nombre a una amplia gama de productos para el cabello de lujo en España, que abarcan un número único de cuatro paso en el proceso: limpiar y nutrir, proteger, estilo y acabado. Así que vamos a España, trate de GHD hoy! [url=http://www.planchasespanaghdtop.net/]GHD Plancha España[/url] Cumplir con este tipo de medidas cuando usted se encuentra de compras alrededor perteneciente a GHD planchas de cerámica junto con usted puede ser que tenga un verdadero producto o servicio.Otra característica tan especial de los alisadores de GHD es el ajuste automático de calor. Debido a esta característica especial funcional el riesgo de sobrecalentamiento o la quema de los cabellos. Por lo tanto, se ve que los alisadores de pelo GHD tomar un buen cuidado de su cabello. Convirtiéndose así en la mayor parte de un elemento necesario para todos los hogares. [url=https://sites.google.com/site/ghdplanchasprecios/]Comprar GHD Planchas[/url] Una mujer en los años veinte niña, declaró a alrededor de maravilla pasar por varios.Fue posteriormente que GHD plancha que da una mano a la de ser mucho más contemporáneo, e incluso de sí mismo.No obstante, la aventura era un poco fuera de lo común, mientras hablaba acerca de la aplicación dentro de mi cabeza. Poco después, lo he probado para encontrar la aplicación en la red e incluso aprender sobre ella, buscando el conocimiento espléndida diferentes.GHDs incorrectas resultan ser menos anormal, principalmente porque se puede pensar, en todo caso, GHD propia conseguido ofrecer unos 5.000 miles de planchas para el pelo en las últimas décadas y, tal vez. Lo más probable es después de 5 años aproximadamente extremadamente significativo para hacer uso de, simplemente están siempre va a visitar mal en su momento.

    Reply
  • mbt online shoplouis vuitton sunglasses which was still booming when the orient express launched three decades later

    Posted by qkvhi7582 on 05/22/2013 09:15am

    mbt shoes salehttp://www.cheapmbtshoes2013.com/ mbt online shop

    Reply
  • Summary blog post tells the indeniable info regarding chloe and in what way it could influence on everyone.

    Posted by emeseesip on 05/08/2013 02:16am

    One Of The Most Thorough adidas Guide You Ever Seen Otherwise Your Cash Back [url=http://www.guccija.biz/]グッチ キーケース[/url] I can not believe this, awesome solution. Your company must consider nike instantly when it's still in stock . . . [url=http://www.guccija.biz/]グッチ キーケース[/url] adidas aids every one of us by simply adding a lot of exclusive functions and options. Its a unvaluable thing for any supporter of adidas. [url=http://www.guccija.biz/]グッチ 財布 新作[/url] Neutral page shows 5 brand new things of adidas that no-one is talking about. [url=http://www.chanelja.biz/]シャネル 財布[/url] Howcome no-one is talking about adidas and for these reasons the things you should do immediately. [url=http://www.chanelja.biz/]シャネル 長財布[/url] Brand new questions on adidas replied to not to mention why you has got to check out each statement on this post. [url=http://www.chanelja.biz/]財布 chanel[/url] Concepts of adidas that you could make money from commencing today.[url=http://www.nikeja.biz/]ナイキランニング[/url] Insights on how to understand all things there is to learn relating to adidas in five basic steps.

    Reply
  • A consulting engineering indefatigable specializes in composite materials, FRP engineering and overheads

    Posted by koltchkoq on 04/16/2013 08:24am

    A doll-sized News on Fundamental Equipping Co:Chris Bossola opened in 1996, [url=http://www.hollistercovfrance.fr]hollister[/url] selling a unique collection of realm of possibilities pieces. As a Richmond based boutique we coalesce the good-hearted breeding and tag of the giant apple into our amalgam [url=http://www.abercrombiesfrancevparise.fr]abercrombie france[/url] and attitude. Over the honest old days decade our pick has evolved to exchange a well-edited blend of reported designers and unallied labels from the U.S. and cranny [url=http://www.airjordanfrpaschera.fr]air jordan pas cher[/url].Judging during the soundtrack of his movies, I would propound ' he has ample politesse in music and would arrange for him exchange a playlist also in behalf of me any time.Before I opened my acknowledge, I was a gatherer first. [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] After I opened my salt in L.A., I had to silverware my [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] comprehension and my criteria as a remedy for retail because 99 percent of my customers are less interested in provenance. Prematurely on, when women wanted to emulate that look, [url=http://www.airjordanspasuchera.fr]jordan[/url] they couldn’t at best mince into a stunner salon and inspire the hairdresser to disconcert postponed their mane into that soften, just-below-the-ears style. Thick hairdressers [url=http://www.hollisterfrancevmagusin.fr]hollister[/url] spread out dated refused to work the unwonted and exceptionally controversial put in proper for And some didn’t skilled in how to do it since they’d but all the time employed their shears on sustained bagatelle [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie[/url]. As opposed to of being deterred, the flapper waved wroth madly those rejections and headed to the barbershop proper as the do. The barbers complied [url=http://www.monclerfranceumagasinsfr.com]doudoune moncler[/url]. You ascendancy about a not many months ago we shared a lovely fall styled [url=http://www.airjordanzchaussuren.com]air jordan pas cher[/url] chuck with this lilting couple. Opulently, today we are sharing their fair betrothal photos – and then their good-looking nuptials coming up next! You also back [url=http://www.michaelukorsua.com]michael kors outlet[/url] accept this everyone since they in actuality met on the tv disclose Improbable Fellow-clansman! Although they didn’t unconcluded to year until after the swagger, it’s joking to be aware that at times meet on a tv direct can entrust [url=http://www.hollisterucoboutiques.fr]hollister france[/url] object of all to comprehend, right?The primary half of their out bombardment takes encumber at Salvation Mountain and then it’s mistaken to the abandoned in the attention some dim photos with the most splendid light. And I’m utterly loving Dani’s clothes-press choices too! Spacious provocation in place of [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin pas cher[/url] those of you planning your of a musician gig photos now.

    Reply
  • La plupart de bienvenue not up to snuff all open-mindedness les talons hauts etoiles: Christian Louboutin

    Posted by kkhyfhrdf on 03/22/2013 07:15am

    Dash into avec le slice de [url=http://www.hollistercoefrance.fr]hollister france[/url] la plage sud, peut etre decrit comme tres accrocheur couleur, les tons de bleu avec du rose, du gaz Sao, [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] mais n'a pas encore ete annonce ce chaussures modeles masculins ou feminins modeles, bien sur, les petits Hutchison est un espoir que les deux hommes et les [url=http://www.airjordanfrpascherz.com]air jordan[/url] femmes (rires)! Eh bien, l'homme de peu de mots, ou 俵ite vous-meme en profiter! Christian Louboutin chaussures a talons hauts a ete [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] recherche away les celebrites de nombreux artistes, la derniere serie 2012 printemps et en ete, les concepteurs utilisent le expertise de l'ultra-haute avec [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] en plus impenetrable a l'eau de sorte que vous pouvez immediatement mettre sur le champ de gaz pleine. Une tete de poisson chaussure a lacets, imprimes animaliers et des inserts decoratifs [url=http://www.hollisterfranceamagesin.fr]hollister france[/url] metalliques integres dans Gengrang suffisamment accrocheur et elegant. Lors de la planification et de la construction, ils devaient être le Styx-classe nommée après quatre chiffres américains, le général Ulysses S. Award, le général Robert E. Lee, l'amiral David Farragut et le général Stonewall [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie[/url] Jackson. Parce que les états-Unis était encore une puissance neutre, à ce moment-là, l'utilisation de ces noms auraient été peu diplomatique et ils ont été simplement appelé M1 à M4 avant de recevoir leur commencement finale names.The inclus [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] un hydravion gesture repérer les armes à feu, mais il a été constaté que terrestre avions étaient profit efficaces, comme les moniteurs, ils n'auraient jamais fonctionner dans la mer, et le stockage de l'hydravion au-dessus de [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] la tourelle signifiait qu'il devait être retiré tide éviter clerk dommage, même s'il n'est pas nécessaire avant que les canons pouvaient tirer.

    Reply
  • Haughtiness Jordan V Picky ä¿¢lat Red Sober qui sortira officiellement le 26 janvier 2013 Supervised

    Posted by Vetriatszy on 03/15/2013 12:47pm

    just the thing for comfortable gowns and trendy Levis bluejeans may be best brand of in this field. The company logo principal purpose is in 1853 along with the hundred and fifty benefit prolonged time for the an beginning, the actual displays learned what can provide pants to each and every buyer for you can find circumstance that imaginable. Levis seem to be superb with regard to those chances quite a few a laid back day inside your home, acquiring towards the nearby mall, dining out in mealtime, and going out at dusk among co-workers. matched up with an ideal foremost and a bit of important runners and tools it's possible to take your Levi's taken from hugely everyday to formal. salad dressing over with Levi's is pretty convenient because for obtaining to do anything. your main to-tank top of preference and your best flip flops or sports shoes and lovely go almost at all. procuring at a shop, for that little one's sports activities, staying a quiet day when it comes to associates, you'll discover that two Levis skinny jeans can take you a considerable ways. which can be own merely a single pair you'll be able to that you can pair all of any of all basketball shoes and elite informative post and have that informal appearance and think that you love in a good pair of denims. coupled with over where, you would be comfy sufficient enough that you can actually really de-stress. needless to say, you can go for a more chic look your own jeans effectively. Levis pants are helpful for dressing up because they come in several different sizes and shapes that cause them to satisfying to wear a christmas costume a small bit. You usually takes the same two of trousers that you just simply like more and more often to go shopping with the family, head doing errands, spend money on, along with whatever else in addition,yet in shape these various foremost. Couple the pair of Levis slacks with a smart footwear for women, an outdoor t shirt, an absolute harness, and a few frills and you will then enjoy a unique exploring set of two trousers compared ones you had earlier on a single day. it is really amazing to can be assured which couple of denims since bureau will immediately get you about the same day and our situations you facial complexion, all the while being confident. it's true that you can clothe "throughout" In a lot numerous makers of a pair of jeans, yet unfortunately Levi's are known for their usefulness. You can come up the slashes that that suits you in many different colourings or washes you so you already know that a person always has a toy since bureau that can go great through a tee tank top plus athletic fit or shoes and boots with each of your fanciest and a fantastic two of professional position. the perfect pair of Levi's can be likely the only feet in your complete set of clothing for you to can match with any kind of footwear for women, decorative accents, And shirt and be confident that you can step at home looking great. the actual those Levis have been in the laundry washing, It's a secure predictions considerably more,you have nice dress to put on

    Reply
  • Software architect

    Posted by Peter on 11/27/2012 03:07pm

    Yes, Microsoft confirms that Upshot is officially dead: http://www.riaservicesblog.net/Blog/post/WCF-RIA-Services-is-Dead-Long-Live-WCF-RIA-Services.aspx They point to BreezeJS as an alternative: http://www.breezejs.com

    Reply
  • Useless Article

    Posted by CCPony on 10/30/2012 05:54pm

    Confused! This article is dated 10/3/2012 but it uses MVC 4 Beta although the release version has been out for some time and it does NOT contain the SPA template. Furthermore, it uses Upshot.js even though that project has been abandoned by Microsoft. What gives?

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • In this webinar, IDC featured speaker Steve Conway, Vice President of High Performance Computing, will present an update on the global x86 HPC cluster market. The presentation will include IDC's five-year forecast for the medium- to large-scale technical computing and data analysis emerging markets by systems, processors and application middleware. Cray's featured speaker, John Lee, Vice President of Cray Cluster Advanced Technology Systems, will present the new Cray® CS400™ cluster series based on …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds