Site Meter
 
 

Single Page Application packages and samples

This post is for you if you saw my ASP.NET Single Page Applications presentation at recent conferences and would like to try out the code for yourself.

Getting the post-beta tools update, and running the scaffolder

First, make sure you have ASP.NET MVC 4 Beta. Then if you want to scaffold up a simple data-editing SPA,

  • Create a new MVC 4 project. Choose the Single Page Application subtemplate.
  • Once you’ve created the new project, pop open NuGet package console (View > Other Windows > Package Manager Console), and install the latest scaffolder templates as folllows:
Install-Package SinglePageApplication.CSharp

Or, if you’re using Visual Basic instead of C#, install the VB package instead:

Install-Package SinglePageApplication.VisualBasic

Don’t skip this step, otherwise you’ll be using the old beta SPA templates and the result will be much less interesting.

Note that Visual Studio may give a false compiler error (“The type or namespace name ‘MvcTextTemplateHost’ could not be found”) – you can either just ignore it, or restart Visual Studio to make it go away. This is an unfortunate limitation of the way we’re packaging this post-beta update, and won’t affect the final tooling.

  • Now you can follow the on-screen instructions in /Models/TodoItem.cs to scaffold a simple data-editing SPA. Use the Add Controller dialog as explained in the comments on that file, remembering to build the solution first, and then you can run the app and browse to http://localhost:whateverport/Tasks.

image

If you want to learn what the point of all this is, see http://www.asp.net/single-page-application or watch this presentation.

Getting the DeliveryTracker sample

If you want to see a slightly bigger and more fun app built with the same libraries and architecture, you can get hold of the DeliveryTracker app that I built during the SPA presentation. If you want to see the mobile UI, you’ll want to either use a real mobile to view it, or fake your useragent (instructions for IE or Chrome or Firefox).

image

Note that the source on GitHub doesn’t include the offline support, as that’s still very early in development – the design and functionality is still likely to change significantly.

77 Responses to Single Page Application packages and samples

  1. Todd Thomson

    Any ballpark timeline for offline support?

  2. Vitaly

    Hi! I have a little problem here – I did everything as you wrote, but ToDo list isn’t working for me – whenever I try to add/edit/delete item (yeah I added some items into the database from SSMS just to see if they will show on the web page, they do show up), nothing happens – data on webpage doesn’t change, database doesn’t change.
    Is there something I’m missing here?
    Thanks

  3. Eric Miller

    Tried out the Delivery Tracker app and it works. Having an issue with the text size rather tiny on the Windows Phone emulator.

  4. Ryan

    Whenever I try to add a new SPA controller my Visual Studio 2010 freezes, I wonder if this is because I had a developer preview of visual studio 11 installed?

  5. Ryan

    I realize the offline support is a future feature, but how do you plan on handling conflicting changes from multiple offline users? Last in wins? Concurrency exceptions?

  6. Mark

    When trying to run the sample I get the following exception: {“Exception has been thrown by the target of an invocation.”}. It occurs while trying to execute the following line in index.cshtml:
    @(Html.UpshotContext(bufferChanges: true)
    .DataSource(x => x.GetTodoItems())
    .ClientMapping(“TodoItem”))

  7. Mark

    Following up from my previous comment. The InnerException is:

    “Failed to get the MetadataWorkspace for the DbContext type ‘DeliveryTracker.Models.DeliveryTrackerContext’.”}.

    In your video you mention that the first time you access the page, that it builds the database. Can you provide more details on this? I’m running Visual Studio 11 Beta and SQL Server Express 12. Also, I’m running on Windows 8.

  8. SleepyDaddySoftware

    Mark: That assumes you’ve got the default SQLEXPRESS instance running on your dev machine, which I didn’t have running either. I had to setup a new connection string for a SQLServerCe local database. Replace the default connection string with something like this:

    The AnyNameYouWant.sdf local SQL CE database file will be generated by entity framework the first time your page is spun up, if it doesn’t already exist. Note the name=”…” property has to be the same name as your DbContext class, or it won’t work. EF Code First looks for this by convention.

  9. SleepyDaddySoftware

    OK, it doesn’t like the brackets, so I’ll leave them out, but you’ll have to add them in yourself:

    BRACKET add name=”NameOfYourDbContextClass” connectionString=”Data Source=|DataDirectory|AnyNameYouWant.sdf” providerName=”System.Data.SqlServerCe.4.0″ CLOSEBRACKET

  10. Eric

    To fix the problem with getting the TodoTasks to work, you need to fix a bug in the connection string in the Global.asax.cs

    Data Source=(localdb)\v11.0

    should be

    Data Source=(localdb)\\v11.0

    Also, I think you need to add the catalog to the connection string.

    In the server explorer, under the Data connections there is a default connection. If you look at the properties for it, you’ll see a connection string that includes and Initial Catalog parameter that looks something like this:

    Initial Catalog=aspnet-SpaTest2-20123823642;

    You need to add that to the string as well.

    My line looks like this:

    Database.DefaultConnectionFactory = new SqlConnectionFactory(“Data Source=(localdb)\\v11.0; Initial Catalog=aspnet-SpaTest2-20123823642; Integrated Security=True; MultipleActiveResultSets=True”);

  11. Mark

    SleepDaddySoftware / Eric… Thx for guiding me to the Global.asax.cs file for the database string. I was finally able to adjust the string to work with the SQL Server Express 2012 version I installed.

  12. SleepyDaddySoftware

    I couldn’t get the delivery tracker sample to work. Every attempt to POST data back to the server, the server responds with status code 405 (method not allowed). The post is on /api/DataService?action=/Submit and the response body is “The requested resource does not support http method ‘POST’.”. The GET requests seem to work fine though.

  13. Hi Steven

    Does this template support complex models?
    It worked for me with the given TodoItem model.
    However, it failed once I added a TodoType property to TodoItem model (with a foreign key).

    Many thanks

  14. Joe

    Hi Steve,

    Are these resources going to be expanded to include example of using repository or service layer? At the moment it seems all the business logic and data access would go in the controllers.

    Cheers
    Joe

  15. Jahmani

    Great work

    but I have a single problem
    When I try to add A model with a DateTime field, in the resulted View I got the following error

    Server error: HTTP status code: 500, message: There was an error deserializing the object of type System.Web.Http.Data.ChangeSetEntry[]. DateTime content ’1/2/2012′ does not start with ‘\/Date(‘ and end with ‘)\/’ as required for JSON.

    any suggestion to overcome this exception

  16. I am experiencing the same problem as SleepyDaddySoftware. every POST results in 405

  17. To overcome error 405 I simply chaged the routing definition in the Global.aspx, like this:
    routes.MapHttpRoute(
    name: “DefaultApi”,
    routeTemplate: “api/{controller}/{action}”
    );
    This will generate http://URL/api/Controller/Submit link rather than the “?action=Submit” (which causes the 405).

  18. I have a problem with a bit more complex model. Let’s say I have a list of objects A each with a list of objects B, each one with a list of object C.
    Getting the data works ok, showing them on screen works ok and changing the properties of any object (even the C objects nested deeply) will post the changes, both in the immediate scenario and in the buffered scenario.

    What is not working is the “revert” changes in the buffered scenario, that seems to work only on the properties of object A (so the first node of the ViewModel let’s say). I am doing this: self.revertAll = function () { self.dataSource.revertChanges(); }; but to no avail, it just does nothing.
    Another thing that does not work is the “IsUpdated” property, with knockout complaining that it’s a missing mapping. I can see it defined in the upshot.compat.knockout.js file but apparently it is not working… I am wondering (shot in the dark here) if it is simply a problem of timing, meaning that knockout is trying to bind properties while upshot is still downloading the list of entities so it is kinda “incomplete” if you know what I mean. It is strange tho since everything else is bound ok… :/

  19. Fixed the previous bit… Did not install the SinglePageApplication package :P

    Anyway, now everything works, but I was wondering if it is possible to add a Global IsUpdated property to the model which will take into account modification in the nested arrays as well… Mind you, probably rolling our own is not that hard…

  20. SPA and Scaffolding are marvelous, I am very happy to see your excellent work in this release Steve! Any chance you can lose the dependency on the EF before final release? I would very much like to use this (overriding templates of course) with a Document Database (RavenDB) and not have to do all my work with the EF hanging around, then excising it after all the scaffolding is finished.
    And THANK YOU SO MUCH for supplying the VB Templates!

  21. Fred

    @Jahmani

    That’s cause JSon doesn’t specify how to display date-values and so MVC (as well as WCF) expects Dates in the format

    \/Date(xyz+00:00)\/

    wheres xyz are the seconds since 1970 and 00:00 is the offset of your timezone.

    So, you have to transform to/from this format. knockout.js will help you doing so providing a hook for transformation-functions.

    Wishes,
    Fred

  22. Manfred

    @Steve

    The version of the sample on the mentioned git-hub-page does not include all the things you show at channel9. For instance, the offline-stuff is missing. I understand, that this isnot finished yet, but can you provide us with this full example, anyway ?

    Wishes,
    Fred

  23. Dave

    Hi Steve,

    Excellent presentation. Quick question though. I just browsed the source and couldn’t seem to find the meta tags you added to help make the app feel more native on the iPad. Any chance of getting those into the _Layout.Mobile?

  24. Jim

    In your book for MVC3 you gave instructions on how to setup Ninject in an empty project. How would you set that up for an MVC4 empty project? They seem to be a bit different. Thanks!

  25. @SleepDaddySoftware I had the same problem as Mark. I added the second slash to the Global.asax and the Default connection string and the ToDoList came up. That did it. I did not need the Initial Catalog entry in the Global.asax.

    I am stoked to finally get to play with this template. Thanks for the help! I think I can start to work through the Delivery presentation now.

  26. Sagy

    Great presentation.

    I’m trying to follow the steps on a new project but I can’t seem to use Html.UpshotContext.

    Do I need to reference something?

    Thanks,
    Sagy

  27. holgi

    I have no connection string in the Global.asax.cs ?
    Everytime the sample app looks at SqlServerExpress ?
    Where i could change this ?
    thx
    holgi

  28. Jahmani

    Thanks Fred for the hint
    This is the workaround for the Json Date Time problem, just add a new observable to the viewmodel:

    self.Date = ko.observable(data.Date);
    self.DateJson = ko.computed({
    read: function () {
    if(self.Date() != undefined)
    {
    var DateObj = new Date(parseInt(self.Date().replace(“/Date(“, “”).replace(“)/”, “”), 10));
    return DateObj;
    }
    else
    return self.Date();
    },

    write: function (value) {
    var formatedDate = “\/Date(” + Date.parse(value) + “)\/”
    self.Date(formatedDate);

    }
    }
    );

  29. holgi

    Where i can change connection string ?

  30. Mike

    Quick SEO question:

    – Am I correct in assuming that this approach faces the same SEO challenges that other AJAX/Single page approaches have?

    So, you still need a static version if you want search engines to find it – even with the addition of back, forward, history and deep linking (which makes for a great user experience).

  31. Mike

    For those having trouble with @(Html.UpshotContext)

    –> try adding a reference to: System.Web.Http.Data.Helpers2.dll

    apparently it’s in there…

  32. Mike

    One more thing, I noticed that you need to set the allowRefreshWithEdits option to true in order for “Hide delivered items” to work properly.

    So, in DeliveriesViewModel.js, change the 3rd line to:

    –> self.localDataSource = upshot.LocalDataSource({ source: self.dataSource, autoRefresh: true, allowRefreshWithEdits: true });

    IDK if this is a change to upshot or something else.

  33. Carl

    This was a great presentation. Hoping to see future implementations without using the Entity Framework as that’s not an option for me.

  34. Mike

    +1 for NOT requiring Entity Framework!

  35. Martin

    “+1 for NOT requiring Entity Framework!”

    Agree!

  36. John

    “+1 for NOT requiring Entity Framework!”
    Agree!

  37. ShantanuChandra

    Microsoft JScript runtime error: ‘upshot’ is undefined

    what do I get this and
    how do I cure this error???

  38. I ended up having to add this to the DeliveryTracker web.config to get it to load.

    Was getting an error on this line
    @(Html.UpshotContext(bufferChanges: true).DataSource(x => x.GetDeliveriesForToday()))

  39. Re: Mike’s SEO question.

    I don’t think this type of setup is best for pages that would need SEO. This approach is to build applications. You’d want something separate for your sales pages.

  40. BelgiumMVC4

    On Github the Bin folder isn’t included. Where can i find the Helpers2.dll ?
    Thx !

  41. Bill

    This line of code in DeliveriesViewModel.js is failing:

    self.deliveriesForCustomer = self.deliveries.groupBy(“Customer”);

    I get the error message: “Microsoft JScript runtime error: Object doesn’t support property or method ‘groupBy’.”

    Any ideas anyone? Thanks!

  42. Peter

    Hi Steve,

    Really love what’s going on here. Great work!

    Can or at least will upshot ever support beyond EF?
    Would be great to be able to use other data source types.

    Thanks.

  43. Necmi

    Hi Steve,

    Can we use extjs framework in clientside? Instead of knockout?

  44. Anish

    “+1 for NOT requiring Entity Framework!”
    I also agree!

  45. Jon

    “+1 for NOT requiring Entity Framework!”

    Pretty please. :)

  46. aLeX

    HI bill
    got the same message:
    This line of code in DeliveriesViewModel.js is failing:
    self.deliveriesForCustomer = self.deliveries.groupBy(“Customer”);
    I get the error message: “Microsoft JScript runtime error: Object doesn’t support property or method ‘groupBy’.”

  47. Richard

    If you are getting the error “Failed to get the MetadataWorkspace for the DbContext type ‘DeliveryTracker.Models.DeliveryTrackerContext’.”

    I fixed this by changing the connection.String name in your Web.Config from “DefaultConnection” to the name of the DbContext for your project, “SinglePageDemoContext” in my case.

  48. Buddy

    I am having great success with a healthcare app that I have converted to MVC4. Works with different functionality for desktop, iPad and iPhone.
    However, I need to point the web.api to an existing database. I have changed the “defaultconnection” in the web.config, but the app still gets data from the original sqlexpress created by code-behind.

  49. For anyone else struggling to get nav.js working without a dependency on Knockout.js, you need to change line 138 of nav.js from:

    _this.entries().splice

    to

    _this.entries.splice

  50. cb

    Since taking the latest Knockout (v2.0.0.1) and Upshot (v1.0.0.2) update, I’ve been getting an error:
    “SCRIPT438: Object doesn’t support property or method ‘getFirstEntity’”

    on this line of code in the tasksviewmodel.js file:
    self.editingTask = editorDataSource.getFirstEntity();

  51. Matthew Paul

    On the delivery tracker sample I got an error about missing a reference to entity framework (coming from line 11 of the index view), even though I could see the reference to EF.

    I used nuget to update to EF4.3 which also adds some lines to the web.config. Just added the database and changed the connection string and it works now:

  52. How would we upload an image using this if
    1. we had an image type in the database
    and/or
    2. we had a text type for the image path/name
    ?

  53. Deepak

    Hi Steve,
    Is SPA a waste of time. While doing the BigShelf SPA project in VS11 Beta and EF5.0 Beta. I could not even get started as they are incompatible.
    See the following bug http://connect.microsoft.com/VisualStudio/feedback/details/732908/asp-net-mvc-4-template-spa-net-4-5-and-ef5-beta-dont-work-together

    Following the second of the only two results by google on the error message
    http://aspnetwebstack.codeplex.com/discussions/351701

    I read a message by “Brad Wilson” that SPA will not be a part of MVC4.

    Yes, as per the roadmap http://aspnet.codeplex.com/wikipage?title=ASP.NET%20MVC%204%20RoadMap

    Yup, there is no SPA in MVC4. Can you shed some light on this. I’ve spend two months reading this and stopped my previous developments as I think SPA would be a better way forward but if this is not happening, please let me know.

    Thanks.

  54. Marco

    Hello Deepak,

    Personally i definitely don’t think SPA is a waste of time. On the MVC4 roadmap it says: SPA won’t ship with the final MVC 4 release, but will continue to evolve outside of the MVC 4 release.
    After reading this i think it will not be a part of the MVC4 installation but it will probably be distributed through NuGet, and in my opinion this is just as good as being part of the MVC4 installation, if not better.
    I really do hope Steve, and the other guys working on SPA, will continue doing so because SPA is freaking awesome :-)

    For people looking to use Upshot without Entity Framework: this is possible.
    Upshot has no dependency on DbDataController but it requires DataController. The DbDataController is the DataController implementation for use with Entity Framework.
    I’ve created a sample application where the MVC project has no dependency on EntityFramework and uses Upshot with the DataController.
    There are some requirements you need to take care of before Upshots understands what data to expect but these requirements are small ones.
    The most important one is that you need to add the KeyAttribute in your POCO-class on the appropriate property.
    I plan on describing this scenario on my blog in a couple of days, i’ll post a new message here when that’s done.

    If anyone’s interested, i have the sample application (keep in mind it isn’t perfect yet :) ) running on Cytanium’s free 4.5 beta server : http://marcovan_kimme.aspnet45.cytanium.com

  55. cb

    @Matthew Paul
    How did you update to EF4.3? Nuget is showing 4.3.1 as the new version, and when I install 4.3.1, the Add Controller dialog doesn’t recognize any model classes.

  56. Lokesh

    Hi Steve,

    How about the security in the upshot. Can the contents be hacked. Can you please explain on this.

  57. Mike

    Marco – looking forward to your post! Can you give the URL for your Blog?

  58. Richard, I was stuck on the “Failed to get the MetadataWorkspace for the DbContext” error. Your post for changing the name of the ConnectionString in the We.config worked for me as well. I also added the initial catalog to the string.

    Thank you!

  59. Deepak

    @Marco, I’m completely sold on the idea of SPA. I’ve spent last 2-3 years write the same in WPF, Silverlight and Windows Phone.

    My question was shall I use the tools, scripts and methodology presented by MVC4 or are there better and most probably other softwares which will see the day of light.

    Good times you have just listed your application. I’ll have a look and come back to you.

  60. Mike

    Great post Marco on using SPA without EF.

    I read somewhere that UpShot will also handle validation. Have you seen posts which describe how UpShot/Knockout will work with validation?

  61. xiao

    Hey

    Can you elaborate on the phonegap part(what you did not cover in your presentation). I am confused on how that would work as you can’t run asp.net mvc in phonegap. So would the asp.net mvc be more just webservice calls or what did you mean?

  62. Mike

    What happened to SPA in the RC?!? Sheesh, the one thing I was really excited about and it’s been moved “out-of-band” and there’s no info to be found saying when it’ll be ready.

    http://www.asp.net/single-page-application says see the Codeplex site and Codeplex says to see http://www.asp.net/single-page-application. Its a circular reference.

  63. sitem00n

    Hi,
    After installation of the MVC4 RC, and running Install-Package SinglePageApplication.CSharp, i could not get the subtemplate of SPA within the MVC 4 template. Did i miss anything?

  64. sitem00n

    The major changes from ASP.NET MVC 4 Beta in this release are summarized below:

    Removed ASP.NET Single Page Application: ASP.NET Single Page Application (SPA) shipped with ASP.NET MVC 4 Beta as an early preview of the experience for building applications that include significant client-side interactions using JavaScript. SPA won’t ship with the final MVC 4 release, but will continue to evolve outside of the MVC 4 release. Check out the ASP.NET SPA home page for details.
    ———-
    I got this from the RC release note. Well, how can we get the project template of SPA now? any place to download the zips?

  65. Mike

    Steve – I think you asked for feedback / what are people using – check out:

    http://meteor.com/

    Wow…Granted its beta, has no security, etc. But, it’s similar to SPA.

  66. Jay

    Thanks for giving us the preview. MVC4 RC without SPA is pretty lame.

  67. shashi

    I wrote a complete dashboard with SPA model, I have been scrambling to upgrade to RC before releasing end of this week (which is not likely going to happen).

    Tons of issues: SPA is not a part of RC, even DbDataController is not working anymore (The type or namespace name ‘Data’ does not exist in the namespace ‘System.Web.Http’). This is just one of many.

    You guys mentioned beta is fully supported, does that means I need to live in ‘beta’ forever? what a mess, Microsoft never changes (looks like we use the term contract all the time but never know what it really means).

  68. There are basically two solution if you want to go forward with SPA after installing the RC:

    Either move along with the active development and correct issues yourself:
    http://peterporfy.wordpress.com/2012/06/18/deliverytracker-with-asp-net-mvc-4-rc/

    Either take a step back and include the beta SPA bits in your MVC4 applications:
    http://bartjolling.blogspot.nl/2012/06/building-single-page-apps-with-aspnet.html

  69. @ Bart Jolling: Thanks alot all info. I made it. wish you to nice day

  70. pi stoff

    This is so typical of MS. This smells like the Silverlight debacle. Get thousands of developers interested in a technology and then drop it like a hot stone…. oh yes, and don’t mention anything when switching/renaming or dropping supporting assemblies. Would it be so hard for them to publish something when they do this. I mean, MVC 4 is at RC stage now. No mention of the disappeared DbDataController class or what the replacement it. In spite of the massive improvement that Nuget gives us, the downside is that the individual dev teams are even more out of sync with each other than ever before. Seriously annoying!!

  71. Devon

    I have gone through with Video – Steve Sanderson.but i couldnt find UpshostContext parameter called provider,

    i need to add Provider:”OfflineProvider”

  72. I really saves time, was developing such a study is a useful article

  73. Thank you very much sir your site is a unique resource in javascript

  74. Graham

    Hi Steve,
    I used your DeliveryTracker sample and updated the latest upshot with Nuget in VS2010 … all seemed to be working perfectly with offline support, which is a real bonus.
    However, when I implement the manifest for offline caching (as per your video) it all goes a bit wrong. Have I made an error in my code / manifest, or is this simply not supported yet?
    Thanks,
    Graham