Pages

Saturday, September 6, 2014

How To: Create an Asp.Net Web Forms Application with Bootstrap and Web API

Idea:
The idea of this article is to help you upgrade your existing project to satisfy current Html5 responsive design needs and to make it lightning fast by eliminating all server round trips. Basically we are trying to eliminate ViewState from the page to make it light weight on the client side. 

Summary:
In this article we are going to create an Asp.net web forms mobile first application using Bootstrap to design the layout, Web API as a service layer and jQuery for all asynchronous calls to the server. This way we could eliminate most of the code-behind logic and achieve tremendous performance boost.

Process:
A) Create a simple asp.net forms application using bootstrap template
B) Create bundle to optimize web resources
C) Add a service layer (Web API) with JSON format to the existing application

A) Create a simple asp.net forms application using bootstrap template
1. Start by creating a new Visual C# project in Asp.net and select an “Empty Web Application” from the New Project dialog. Click OK to create new project. (I used VS 2012)

  
Now your solution looks like this


2. Go ahead and create a Global.asax file to the project (We will update this later)
3. Right click on the project and select “Manage NuGet Package…” to install jQuery and then Bootstrap. This will create three new folders “Content” for CSS, “fonts” and “Scripts” to the project.

 
Note: I prefer to delete all .min.* and .map files from the newly created folders and use bundle technique to optimize web resources (will be discussed later)
Also, there is a new file “packages.config” created within the project where we can find all installed NuGet packages and their versions.


Warning: If there is a mismatch in package version between the installed and the one specified in packages.config file, Nuget gets confuses and will not work as expected
4. Now, we will create a master page (Main.Master) with three sections “StyleSection” in the header, “ContentSection” in the body and “ScriptSection” just before the closing body tag. For this sample we are going to use “Navbar” template from bootstrap templates. Get the source html from browser “View Page Source” and it in our master page at the bottom. Replace with downloaded html to replace and retain the master page behavior.
Note: Here we commented the form tag; If needed we can create form sections within our content page. Now, our Master page looks like this



5. Create a new content page “ContentPage.aspx”. Add the html code (div with class “jumbotron”) from the Bootstrap template into the “ContentSection”. Our code should look like this

6. Set the “ContentPage.aspx” as start page; build and run the application.
Laptop/Tablet View:


 Mobile View:



Note: If you see our Main.Master page, there are individual references to each of the .css and .js files. This will impact our page load time when there are numerous files added to the page. To fix this we need to create a bundle for Style and Script types.

B) Create Bundle to Optimize Web Resources
7. First we need to create a new folder “App_Start” to the root of the project.
8. Add a new class “BundleConfig.cs” to the folder with a static RegisterBundles method. Each script or style bundle is located at a virtual path as specified from the root (~/bundles/)



Note: The order in which the files added to the bundle is important; Check for any dependencies
9. To fix the BundleCollection missed reference; Install the package “Microsoft.AspNet.Web .Optimization” from NuGet



Note: Add “System.Web.Optimization;” namespace to the “BundleConfig.cs” file. Replace existing style and script tags with the bundle script pointing to the virtual path. Now, your master page should look like



10. Next we need to register our bundle within Application_Start of Global.asax file. Run the application to check if everything works fine. Now, if we view the page source it still shows individual link for each resource even after creating the bundle.



To see the bundle effect, we need to explicitly enable bundle optimization using the statement

 After enabling the bundle optimization, run the application to view the page source. All three script files combine into single and a minified version.


C) Add a service layer (Web API) with JSON format to the existing application


11. First we need to create a new folder "Controller" under project root directory. By default web forms don’t have Web Api. We need to rely on NuGet Package Manager to search for “Microsoft Asp.Net Web API 2.2” and install the package.


Note: This will also install “Newtonsoft.Json” library to serialize and de-serialize objects. If not, you can always find the package at NuGet.



12. Right click on the Controller folder and add new item. From the templates select Web API Controller Class and create "ProductController".


Note: You will see basic Get, Post, Put and Delete action methods. Comment all the code or extend it. I prefer to delete all actions and start new by adding new action method “GetHelloWorld” to test API
 


We need to set proper routing mechanism in order to access API methods. So let’s do that.
13. Add a new class "
WebApiConfig.cs" to the “App_Start” folder with code below


Note: Add reference to this namespace “System.Web.Http”. If your code throws an error at “config.EnableCors()”, go to NuGet and install Cors (Cross Origin Resource Sharing) package (Microsoft.AspNet.WebAPI.Cors) to access Web API from other domains.
 


14. Now, register our api router to the "Application_Start" method in Global.asax file using
WebApiConfig.Register(GlobalConfiguration.Configuration);
15. Now, try to access the API using the link http://localhost:7656/api/   



Note: We have not specifying the controller and action name in the above link. Those values are set to default values (as “ProductController” and “GetHelloWorld”) in the WebAPIConfig file. The result is seen in XML format which is the default Web API behavior.
16. To get the result in JSON (
JavaScript Object Notation) format; we need to set the media type headers to accept “text/html” using below statement in the WebAPIConfig Register method.

Now, run the api link again and this time you see result in JSON format



To learn more about XML and JSON serialization visit this link

Voila, hope you had a great learning experience. Let me know if you have any suggestions or improvements.