ASP.NET MVC5 + Twitter Bootstrap

Creating an ASP.NET MVC 5 Project

Model-View-Controller (MVC) is a software architectural pattern that divides software application into three parts.
Model consists of the business logic and functions.
View is the representation of the information. These information can be illustrated through graphs or charts or any of the user interface that the user interacts with.
Controller receives input from view and model.

1. Visual Studio -> New -> Project -> Under Web -> ASP.NET Web Application
2. Choose MVC template — this will create a default template with MVC folders.
Another template is Web API which will add API folder for REST HTTP calls.
ChoosingWebApi
3. Run the app to make sure it’s compiling and building properly.

Twitter Bootstrap 3 Discovery

What is Twitter Bootstrap? Twitter Bootstrap is an open-source tool that helps in creating websites or web applications. This tool includes pre-developed HTML and CSS templates for arranging html components (Grid-System), forms, buttons, charts, and other navigation components that we normally see in a responsive web application.

Some PROS of Twitter Bootstrap:

  • CONSISTENCY
    Who would not want to see a consistent font and style within a web page? Both developers and users would want to see a consistent flow in a project, so Twitter Bootstrap was built to avoid a confusing layout flow in every web page that users will interact.
  • RESPONSIVE
    Whether it is a huge desktop, a really small mobile screen or a phone with a size like a tablet, Twitter Bootstrap got it covered! This tool is developed to have a responsive layout that caters to all the different screen sizes that any user may have.
  • LATEST AND GREATEST
    Twitter Bootstrap was made by really great developers who used the latest libraries out there: CSS3, HTML5, JQuery… etc. The CSS was developed using LESS platform that allows using variables, mixins, functions inside the CSS page to make CSS more themable and extendable.

By default, MVC5 is using the Twitter Bootstrap template by default. That means, the bootstrap.min.js and bootstrap.min.css are already inside the project and we do not need to download it from Twitter Bootstrap’s webpage to use it’s styles.

Grid System

  • Twitter Bootstrap makes the page responsive to phone/tablet/desktop by adding the viewport meta tag:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
  • Twitter Bootstrap’s grid system scales up to 12 columns.
    This means that all the columns with .col-md-* should add up 12. Any columns after the 12th will be stacked underneath the first 12.
  • Rows are placed inside a class .container for proper alignment.
    <div class="container">...</div>
    
  • Use class .row to create horizontal column groups.
  • Columns are created specifying the number that can add up to twelve. For example, four proportionally sized columns would be: four div with class .col-md-3
    XS = Phones, SM = Tablets, MD = Desktops, LG = Large Desktops
  • GridSystemTable

NOTE: As the browser widens, the smaller-sized classes gets overwritten. As the browser contracts, the larger classes are overwritten.

<div class="row">
    <div class="col-xs-6 col-md-6 col-sm-6">col-xs-6 col-md-6 col-sm-6</div>
    <div class="col-xs-6 col-md-6 col-sm-6">col-xs-6 col-md-6 col-sm-6</div>
</div>
<div class="row">
    <div class="col-xs-4 row-grid">col-xs-4</div>
    <div class="col-xs-4 row-grid">col-xs-4</div>
    <div class="col-xs-4 row-grid">col-xs-4</div>
</div>
<div class="row">
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
    <div class="col-md-3">col-md-3</div>
</div>
<div class="row">
    <div class="col-xs-8 col-md-8 col-sm-8">col-xs-8 col-md-8 col-sm-8</div>
    <div class="col-xs-4 col-md-4 col-sm-4">col-xs-4 col-md-4 col-sm-4</div>
</div>

Other Good Stuff…

Offsetting columns

To move columns to the right, use “.col-*-offset-*”. The first * depends on the screen size which could be written as “.col-xs-offset-, .col-md-offset-, or .col-sm-offset-”. The second * increases the left margin of column by * columns. For example, “.col-md-offset-4″ moves that column over four columns.
offset
As we can see on this example, we could combine the class names “.col-md-4″ and “.col-md-offset-3″ which defines the width of the column then offsets the column to 3 columns (-offset-3).

Like the grid system example, the offsets follow the 12-column way of how the columns are arranged. An example would be doing “.col-md-4″ followed by a div with “.col-md-4 .col-md-offset-4″. Where will the second div be?
nested-offset
So, since the position of the second div (without the -offset-4) is beside the first div, the offset made it so it moved another 4 columns over.

<div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4 col-md-offset-4">.col-md-4 .col-md-offset-4</div>
</div>
<div class="row">
    <div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div>
    <div class="col-md-3">.col-md-3</div>
</div>

Nesting columns

Inside the .row, we can add a set of .col-md-* inside of an exisiting .col-md-*. To visualize it properly…
nested-row

<div class="row">
    <div class="col-md-9">
        1st row .col-md-9 (Parent Row)
        <div class="row">
            <div class="col-md-6">
                Nested 2nd row .col-md-6
            </div>
            <div class="col-md-6">
                Nested 2nd row .col-md-6
            </div>
        </div>
    </div>
</div>

For this example, the parent row (with a class .col-md-9) has a 9 column-width. Since the next row is nested (with 2 .col-md-6) that add up to 12-columns, their TOTAL WIDTH will only extend up to 9 columns (not 12), but they will be evenly divided because both of them add up to 12 columns.
What I mean by that is…
NestedAndNonNestedRows

<div class="row">
    <div class="col-md-9">
        1st row: .col-md-9
        <div class="row">
            <div class="col-md-6">
                2nd row (Nested): .col-md-6
            </div>
            <div class="col-md-6">
                2nd row (Nested): .col-md-6
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-6">
        (Not Nested) .col-md-6
    </div>
    <div class="col-md-6">
        (Not Nested) .col-md-6
    </div>
</div>

IMPORTANT: Nested rows (even when the column-set adds up to 12 columns) follow the max width of the parent row unlike a non-nested row that can span out to 12-column width.

Push and Pull Columns (Column Ordering)

We use the modifiers .col-md-push-* and .col-md-pull-* to change the order of the grid columns.

<div class="row">
    <div class="col-md-9 col-md-push-3">1st column (col-md-push-3)</div>
    <div class="col-md-3 col-md-pull-9">2nd column (col-md-pull-9)</div>
</div>

This code results to:
pushpullTB

For this example, we can see that we pushed the 1st column to 3 columns to the right and pulled the 2nd column 9 columns to the left. Since the columns are also 9 and 3 column-width respectively, they just switched places.
IMPORTANT: In other words, we use -push- and -pull- to re-organize our column positions. Unlike offsets, when we “push” a column, it does not affect the position of any other column beside it. For example, if there are 2 columns, and only the first column has a “-push-*” class, the 2nd column will stay in the same place and will not be pushed to the right. Offset, on the other hand, pushes everything to the right of the column that has the -offset-* class.

References:

Twitter Bootstrap 2.3.2
Twitter Bootstrap 3

How to use PhoneGap API + WP7

How to get started?

In my previous blog posts I’ve shown how to use PhoneGap with Xcode and Eclipse in targeting iOS and Android platforms. For this blog post, I will show how to use the PhoneGap API with Visual Studio and the Windows Phone 7 emulator as your development environment.

For this sample project, we will also be using JQuery and JQuery Mobile UI.

Now to get started, PhoneGap has documentation on what tools to download and what steps to follow. After you have your development environment setup, you can look over PhoneGap’s API documentation. The API is not to cumbersome and is straight-forward in following for each of the different device hardware. Most of the API involvrs javascript callbacks as I will show below in example code.

For this blog post, I will discuss how to use the following:
1. Device
2. Accelerometer
3. Camera
4. Geolocation
5. Notification

Most of the API methods and objects will exist on most of the major platforms (iOS, Android, WP7). However, some things will be specific on some platforms. Android and WP7 has a search and back button but iOS doesn’t. The menu button only exists on Android. In general, you should be able to use the PhoneGap universally on all platforms. But its good practice to test and run on each device to make sure it works they way you expect.

The sample project was developed fully in Visual Studio and tested with the Windows Phone 7 emulator. The 5 device hardware features that I will interact with using the PhoneGap API is shown on their own phone screen. The examples are very simple to explain how to use the PhoneGap API.

Below is a screen shot of the sample project’s Solution Explorer in Visual Studio. Notice the “www” folder. This folder is created with the PhoneGap project template and where all your web files (HTML, CSS, JavaScript, etc) exist.

Solution Explorer

Before we dive into the API code for each phone screen, I want to mention when using the PhoneGap API you should place your javascript code inside the javascript event OnDeviceReady. If you place your javascript code that calls the PhoneGap API in here, you can guarantee the device is loaded and ready to interact with. Below is the code included in the index.html file.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing! 
        function onDeviceReady() 
        {

        }
        </script>

Now lets dive into example code.

Device – Gather device specific information

The HTML and jQuery Mobile UI for the Device screen.

<body>
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>Device</h1>
            <a href="#accelerometerpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Device API
            <!--<a href="#newpage" data-role="button">Second Page</a>
            <br/>-->
            <p id="devicename"></p>
            <p id="devicephonegap"></p>
            <p id="deviceplatform"></p>
            <p id="deviceuuid"></p>
            <p id="deviceversion"></p>
        </div>
    </div>
</body>

The jquery code inside onDeviceReady. The device object is from PhoneGap’s API and its value is added to the innerthtml for each #device element.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing!
        function onDeviceReady() 
        {
            console.log("onDeviceReady. You should see this message in Visual Studio's output window.");

            $('#devicename').html(device.name);
            $('#devicephonegap').html(device.phonegap);
            $('#deviceplatform').html(device.platform);
            $('#deviceuuid').html(device.uuid);
            $('#deviceversion').html(device.version);
        }
    </script>

The HTML and jQuery Mobile UI for the Accelerometer screen.


      <div id="accelerometerpage" data-role="page">
        <div data-role="header">
            <a href="#home" data-icon="back">Back</a>
            <h1>Accelerometer</h1>
            <a id="camerabutton" href="#camerapage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Accelerometer API
            <p id="aX"></p>
            <p id="aY"></p>
            <p id="aZ"></p>
            <p id="aTime"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object is from PhoneGap’s API. Here the navigator object calls the watchAcceleration method where the first input is the success callback method, the second parameter is the error callback method and the third parameter is the frequency in millisections the success callback method will fire.

var watchId = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, { frequency: 1000 });

        function onAccelSuccess(a) {
            $('#aX').html(a.x);
            $('#aY').html(a.y);
            $('#aZ').html(a.z);
            $('#aTime').html(a.timestamp);
        }
        
        function onError() {
            // TODO: write error logic
        }

The HTML and jQuery Mobile UI for the Camera screen. Here we will write to the imageuri the fileURI of the image we capture. It will write out the location and filename of the image.

      <div id="camerapage" data-role="page">
        <div data-role="header">
            <a href="#accelerometerpage" data-icon="back">Back</a>
            <h1>Camera</h1>
            <a href="#geolocationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Camera API
            <p id="imageuri"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object calls camera then the getPicture method. The input parameters are similar to the Accelerometer except the third parameter where we define inline the quality, destinationType and Camera.DestinationType.FILE_URI. The file_uri that is returned in the success callback method will be added to the innerhtml at imageuri.

navigator.camera.getPicture(onCameraSuccess, onError, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });

        function onCameraSuccess(fileUri) {
            $('#imageuri').html(fileUri);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Similar to the Accelerometer screen, we will write the lat/lon values to the innerhtml.

      <div id="geolocationpage" data-role="page">
        <div data-role="header">
            <a href="#camerapage" data-icon="back">Back</a>
            <h1>Geolocation</h1>
            <a href="#notificationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Geolocation API
            <p id="lat"></p>
            <p id="lon"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we’re calling the watchPosition of geolocation object and on the success callback method retrieving the lat and lon values.

navigator.geolocation.watchPosition(onGeolocationSuccess, onError, { frequency: 1000 });

        function onGeolocationSuccess(p) {
            $('#lat').html(p.coords.latitude);
            $('#lon').html(p.coords.longitude);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Here we created an anchor tag that will look like a mobile button that will display a PhoneGap notification alert.


      <div id="notificationpage" data-role="page">
        <div data-role="header">
            <a href="#geolocationpage" data-icon="back">Back</a>
            <h1>Notification</h1>
            <a href="#storagepage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Notification API
            <br/>
            <a id="notificationbutton" href="" data-role="button">Click Me!</a>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we use jquery to create a handler for notificationbutton that will call PhoneGap’s API object navigator.notification.alert. When the success callback method is reached it will update the innerhtml text of the button to Clicked.

            $('#notificationbutton').click( function() {
                navigator.notification.alert("You clicked me!", onNotificationSuccess, "Click", "Ok");
            });

        function onNotificationSuccess()
        {
            $('#notificationbutton').html('Clicked');
        }

I hope this helps in getting started with PhoneGap’s API. There is a lot more that can be discussed.

Here is the code for the sample project.