Click here to Skip to main content
15,498,622 members
Articles / Web Development
Article
Posted 9 Sep 2014

Stats

561.6K views
22K downloads
112 bookmarked

Create an ASP.NET Web Forms Application using Bootstrap and Web API

Rate me:
Please Sign up or sign in to vote.
4.66/5 (63 votes)
20 Oct 2015CPOL6 min read
In this article, we are going to create an ASP.NET Web Forms application using Bootstrap, Bundle Resources and Web API

Idea

The idea of this article is to help you upgrade your existing ASP.NET 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 lightweight on the client side and all interactions to the backend only through services (Web API).

Summary

This article has been extended into two parts.

Part 1: 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 uses JSON format for better browser understandability. This way, we could eliminate most of the code-behind logic and achieve tremendous performance boost.

In extension to this article on Part II, I have demonstrated how to create a responsive HTML table using FooTable plug-in and apply client side binding using HandlebarsJs JavaScript library.

Part I Process

  1. Create a simple ASP.NET forms application using bootstrap template.
  2. Create bundle to optimize web resources.
  3. Add a service layer (Web API) with JSON format to the existing application.

A) Create a Simple ASP.NET forms application using bootstrap template

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).

Image 1

Now your solution looks like this:

Image 2

Go ahead and create a Global.asax file to the project. (We will update this later.)

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.

Image 3

Note: I prefer to delete all .min.* and .map files from the newly created folders and use bundle technique to optimize web resources (Bundle 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.

Image 4

Warning: If there is a mismatch in package version between the installed and the one specified in packages.config file, Nuget gets confused and will not work as expected.

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 put it in our master page at the bottom. Replace the required HTML with the downloaded source and also maintain HTML to retain its 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:

Image 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:

Image 6

Set the “ContentPage.aspx” as start page; build and run the application.

Laptop/Tablet View

Image 7

Mobile View

Image 8

Note: If you view the source of the 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

First, we need to create a new folder “App_Start” to the root of the project.

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/).

Image 9

Note: The order in which the files are added to the bundle is important; Check for any dependencies.

To fix the BundleCollection missed reference; Install the package “Microsoft.AspNet.Web .Optimization” from NuGet.

Image 10

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:

Image 11

Next, we need to register our bundle within Application_Start of Global.asax file.

C#
protected void Application_Start(object sender, EventArgs e)
{
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}

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 as below:

<script src="<a href="view-source:http://localhost:2469/Scripts/jquery-2.1.1.js"
>/Scripts/jquery-2.1.1.js</a>"></script>
<script src="<a href="view-source:http://localhost:2469/Scripts/jquery-2.1.1.intellisense.js"
>/Scripts/jquery-2.1.1.intellisense.js</a>"></script>
<script src="<a href="view-source:http://localhost:2469/Scripts/bootstrap.js">
/Scripts/bootstrap.js</a>"></script>

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

C#
// Enable bundle optimization.
BundleTable.EnableOptimizations = true;

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

HTML
<script src="<a href="
view-source:http://localhost:2469/bundles/jQuery?v=7cwTEn6KyyUMXFP2b6gmRFCP5GslErEu2IVcRGkvL-s1">
/bundles/jQuery?v=7cwTEn6KyyUMXFP2b6gmRFCP5GslErEu2IVcRGkvL-s1</a>"></script>

C) Add a Service layer (Web API) with JSON Format to the Existing Application

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

Image 12

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

Image 13

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

Image 14

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.

C#
public class ProductController : ApiController
{
   [HttpGet]
   [ActionName("GetHelloWorld")]
   public string GetHelloWorld()
   {
      ArrayList al = new ArrayList { "Hello", "World", 
      "From", "Sample", "Application" };
      return JsonConvert.SerializeObject(al);
   }
}

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

C#
public static void Register(HttpConfiguration config)
{
   config.EnableCors();

   config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{Action}/{id}",
      defaults: new { Controller = "Product", 
      Action = "GetHelloWorld", id = RouteParameter.Optional }
   );
}

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. (This is not required in our sample project.)

Image 15

Now, register our API router to the "Application_Start" method in Global.asax file using:

C#
WebApiConfig.Register(GlobalConfiguration.Configuration);

Now, try to access the API using the link:

http://localhost:7656/api/

Image 16

Note: We have not specified 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. 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.

C#
// To return json return
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

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

Image 17

To understand JSON better, check these samples. Click here to continue reading Part II.

Check this article if you like to start implementing popular AngularJS using Asp.Net MVC

Check this article to know more about Whats New in ASP.NET 5 and C# 6

I hope you had a wonderful time learning new things. Let me know if you have any suggestions. Feel free to rate this article and leave comments for better clarification.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThank You! Pin
Priyanka Kale12-Feb-18 23:26
MemberPriyanka Kale12-Feb-18 23:26 
QuestionThank You For great learning Pin
UmangVerma1-Jun-17 0:27
MemberUmangVerma1-Jun-17 0:27 
QuestionHow to deploy in IIS? Pin
kiransr26-Oct-16 21:26
Memberkiransr26-Oct-16 21:26 
AnswerRe: How to deploy in IIS? Pin
Sreekanth Mothukuru28-Nov-16 21:15
MemberSreekanth Mothukuru28-Nov-16 21:15 
QuestionHow to implement Authentication and Authorization(Token based) Pin
kiransr24-Sep-16 0:12
Memberkiransr24-Sep-16 0:12 
AnswerRe: How to implement Authentication and Authorization(Token based) Pin
Sreekanth Mothukuru25-Sep-16 4:49
MemberSreekanth Mothukuru25-Sep-16 4:49 
GeneralRe: How to implement Authentication and Authorization(Token based) Pin
kiransr26-Oct-16 10:10
Memberkiransr26-Oct-16 10:10 
GeneralHow to add Inline Javascript for a Content Page Pin
Shaibaaz Shaikh31-Jul-16 23:48
professionalShaibaaz Shaikh31-Jul-16 23:48 
AnswerRe: How to add Inline Javascript for a Content Page Pin
Sreekanth Mothukuru1-Aug-16 9:09
MemberSreekanth Mothukuru1-Aug-16 9:09 
GeneralRe: How to add Inline Javascript for a Content Page Pin
Shaibaaz Shaikh1-Aug-16 23:39
professionalShaibaaz Shaikh1-Aug-16 23:39 
AnswerRe: How to add Inline Javascript for a Content Page Pin
Sreekanth Mothukuru2-Aug-16 0:34
MemberSreekanth Mothukuru2-Aug-16 0:34 
GeneralRe: How to add Inline Javascript for a Content Page Pin
Shaibaaz Shaikh2-Aug-16 20:58
professionalShaibaaz Shaikh2-Aug-16 20:58 
SuggestionRe: How to add Inline Javascript for a Content Page Pin
Sreekanth Mothukuru4-Aug-16 9:05
MemberSreekanth Mothukuru4-Aug-16 9:05 
QuestionNice Article and good explanation Pin
Member 1042054128-Jun-16 2:17
MemberMember 1042054128-Jun-16 2:17 
AnswerRe: Nice Article and good explanation Pin
Sreekanth Mothukuru28-Jun-16 3:40
MemberSreekanth Mothukuru28-Jun-16 3:40 
GeneralGood article Pin
exploreCoding22-Dec-15 0:38
MemberexploreCoding22-Dec-15 0:38 
QuestionMy vote of 5 (but) Pin
tutor23-Oct-15 5:32
Membertutor23-Oct-15 5:32 
AnswerRe: My vote of 5 (but) Pin
Sreekanth Mothukuru23-Oct-15 7:10
MemberSreekanth Mothukuru23-Oct-15 7:10 
GeneralRe: My vote of 5 (but) Pin
tutor23-Oct-15 8:25
Membertutor23-Oct-15 8:25 
GeneralRe: My vote of 5 (but) Pin
tutor23-Oct-15 8:27
Membertutor23-Oct-15 8:27 
PraiseRe: My vote of 5 (but) Pin
Sreekanth Mothukuru23-Oct-15 21:18
MemberSreekanth Mothukuru23-Oct-15 21:18 
GeneralMy vote of 5 Pin
Member 120187029-Oct-15 2:58
MemberMember 120187029-Oct-15 2:58 
GeneralRe: My vote of 5 Pin
Sreekanth Mothukuru9-Oct-15 3:04
MemberSreekanth Mothukuru9-Oct-15 3:04 
QuestionProblem on Visual studio 2015 ?¿ Pin
Member 120187029-Oct-15 0:00
MemberMember 120187029-Oct-15 0:00 
AnswerRe: Problem on Visual studio 2015 ?¿ Pin
Sreekanth Mothukuru9-Oct-15 3:04
MemberSreekanth Mothukuru9-Oct-15 3:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.