Tuesday, March 13, 2012

MVC4 Mobile and Desktop Web

As LoB applicatons are what I do on a daily basis, I have been looking at how we can use our existing expertise to build mobile applications.

This is the third component of my analysis (but only the second to be blogged), my android analysis can be found here.

As MVC4 has some improved web applications development features, such as Single Page Application templates, Mobile Application Templates, and the Web API, I decided to use this. I already blogged how the initial project templates were slightly confusing, so this time I decided to start with a standard template, and build from there.

Steps I took to getting up and running


  • Set up the Framework and Business Logic - this is becoming second nature

  • Set up a plain MVC Project

  • Create my page Controller and default view

  • Create my ApiController for the get/post operations

    • I recommend firefox for testing this, IE doesn't do JSON very well and firefox made debugging much easier.

    • Firefox (with the user agent spoofing plugin) also makes it easy to test the mobile enhancements.



  • Create a script for the KnockoutJS ViewModel

    • This included the ajax calls to the ApiController to load and update data. I was unpleasantly surprised to see that while firefox worked immediately, IE10 (win8) required a lot of tweaking and in the end I had to switch from $.getJSON() to $.ajax() jquery calls.

    • As I am creating a multi-page application I defined this at the View level.

    • At this point I also had to modify the 'bundle' in global.js to include KnockoutJS - the default bundle definition did not include this. As a side note, I completely removed the default bundling later on, and created the bundles explicitly. This was necessary to ensure the mobile and desktop script bundles were used correctly.



  • Update my View to use the KnockoutJS bindings



Once this was done, I had a functional website that I wanted to convert to a mobile friendly solution.


  • Install (Nuget) JQuery Mobile

  • Create a new script bundle to include JQuery Mobile js and css files

  • Create a new _Layout.cshtml called _Layout.mobile.cshtml - this should use the mobile script bundle in the script header.

    • This is a cool feature in MVC4, when a mobile agent is detected, the ".mobile" content is rendered, not the standard view



  • Update _Layout.mobile.cshtml to use the JQuery mobile data-role attributes for layout



We now have a mobile styled page and a desktop styled page using a single codebase. The next step would be to update the View to provide better mobile styling features, but I won't go into that here.

No comments:

Post a Comment