Twitter Bootstrap and ASP.NET MVC - Building a Responsive UI

Posted by: Sumit Maitra , on 1/29/2013, in Category ASP.NET MVC
Views: 229743
Abstract: In this article, we will start with the theory behind Responsive UI and how CSS3 and HTML5 support building of Responsive web UI easily. Next we will see how Media queries work. We will explore a well established boiler plate for Responsive UI design – the Bootstrap, by Twitter. We will also see saw how to replace default ASP. NET styling with Twitter Bootstrap and finally create a Project template that can server as starter MVC projects using Bootstrap.

Responsive UI in Web Development is a term that loosely correlates to a design that can adapt itself to various screen sizes. With the proliferation of ‘Web consumption’ devices, most internet sites are no longer viewed on large screen desktops only. Today people view sites from Mobile devices like smartphones with 3” screens to tablets with 10” screens and a variety of sizes in between. The web application you build is expected to be able to handle all these screen sizes gracefully and ‘adapt’ to them. Such design is referred to as Responsive UI.

dncmag This article is published from the September Edition of the DNC Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months.

The September edition featured hot topics like Windows 8 Apps in all shape, form and size - WinRT+C#+XAML, WinRT+WinJS, WinRT+Testing and even a Tiled Web Framework! Apart from that we had WCF 4.5, Testing Benefits, Azure Caching and Hadoop On Azure too! Last but not least, our special guest in the Interview chair. The one and only Jon Skeet!.

Click Here to Download all the issues of this Free .NET Magazine

Ways to build Responsive UI

Sometime back, the official ASP.NET site was revamped to be responsive to various screen sizes. We can see how it changes if we resize our browser.

A scaled version of the two images is as follows:



The behavior of the ASP.NET site is achieved via CSS3 Media Queries and view-port width detection. Thus irrespective of which browser you are viewing it in, the view changes to accommodate itself to the best possible fit. In this article, we will see in-depth how we can leverage CSS3 Media Queries and view-port detection to build responsive UI.

However, another way to support smaller screens is by having independent views for different devices based on Browser/Device detection techniques. Libraries like jQuery.Mobile leverage this. ASP.NET MVC 4 has support for this built-in via the ViewSwitcher Controller and using targeted mobile CSS + JavaScript libraries jQuery.Mobile.

It is okay to choose one way over the other depending on the intended audience and level of interaction required with the site. If the site is all about consumption of information, a CSS3 Media Query approach works fine. However if user interaction involves heavy two way interaction, then a more targeted approach like jQuery.Mobile can be adopted. Finally for high precision activities like Gaming, native applications are a very good idea.

The Meta viewport and CSS Media Queries

The Meta ViewPort Tag

Let get a little deeper into the viewport Meta tag and see how it works. The viewport tag is defined as follows

So what does content=”width=device-width” mean? It means that the width of the ‘area’ of the browser is set to whatever value that current device returns as optimal. Why is this important? If we consider a device with a small screen like iPhone, it return it’s width as 320px, so now if in our web page we set width to 80%, the width will automatically be set to 80% of 320px. Similarly for a desktop browser, the browser usually reports its current width as the device-width. As we can see in the screenshots from our sample, different browser widths elicit different width responses.

Okay great, now that we know the width of our page, how does this help in making them appear ‘nice’ on each of these devices? Answer is CSS Media Queries.

CSS Media Queries

Back in HTML4/CSS2 days there were two different media types supported, ‘screen’ and ‘print’. These allowed explicit labeling of Style Sheets are per the target purpose.

In HTML5 the concept of Media queries was introduced to enable checking of conditions for one or more media type ‘features’. At the time of this article, W3C has thirteen features described, amongst which the most prominent ones are ‘width’, ‘height’ and ‘color’.

If we look a little deep, the picture begins to clear up for us. We can get device-width via JavaScript, and we could then use the width media type feature to check the width and apply different CSS as required.

For example:

@media (max-width: 767px) {
   width: 747px;
   margin-left: 10px;
   margin-right: 10px;

@media (max-width: 480px) {
   width: 470px;
   margin-left: 5px;
   margin-right: 5px;

As we see above, we have used the @media (…) condition to specify a certain condition based on which all classes defined in it are picked up and used.

In the above condition, we have a css class section-width. This sets the width and margin of whatever it’s applied to (e.g. a

). We have setup the media queries such that if the device reports max-width as 480 pixels, the class sets the width to 470 and give a margin of 5px. However if the max-width is reported to be 767 pixels, the class sets the width to 747 and provides a left and right margin of 10px.

The query itself is very simple in this case, wherein we are checking for max-width media feature. As per W3C specs, there are thirteen such media features. You can refer to the spec here.

So a media query is essentially a condition on a particular ‘media feature’ based on which a completely different set of CSS styles can be picked for each condition that is checked.

However building multiple sets of CSS for each possible device is actually a non-trivial exercise. This is where boilerplate like the one for default ASP.NET MVC 4 or Twitter Bootstrap come in and make our lives easier. These templates provide us with a prebuilt set of styles and scripts that have the most common sizes considered and are easy to extend. We are all familiar with the ASP.NET MVC 4 template, following are some of the samples of the default ASP.NET sample in action

asp-net-desktop- tablet-smartphone

The default ASP.NET CSS bootstrap is a good starter template, but is kind of muted in terms of design aesthetics. Towards that end, Twitter Bootstrap is HTML5 + CSS boilerplate, which encapsulates the design aesthetic of Twitter and adds-on Responsive UI elements to help build a modern looking web sites.

Hello, Twitter Bootstrap

The Twitter Bootstrap package consists of predefined CSS styles, Components and jQuery plugins. It is licensed under Apache 2.0 and is free for commercial use. We take a quick look at the Components and plugins available to us before jumping into actually using these components in an ASP.NET MVC application.


Following are the Component Categories at the time of writing –


- Button Groups


- Button Dropdown


- Split Button Dropdown


Nav, tabs, and pills

- Basic tabs


- Basic pills


- Other variations like stacked pills, Tabs with dropdowns, tabs to the left or right.

Navigation Bar



- Inline Labels


Source: Twitter Bootstrap Documentation at



Source: Twitter Bootstrap Documentation at

- There are many more components like Typography (that marks a section of special highlighting), Thumbnails (to show actual image and thumbnails in various layouts), Alerts (classes for highlighting various alert conditions), Progress bars (showing progress of actions).


Apart from the CSS styling classes, the template also comes along with a number of jQuery plugins that are in the bootstrap.js file. These are

  • Modals: for modal dialogs (of course)
  • Dropdowns for creating dropdown menus on buttons etc.
  • Scroll Spy: A nifty plugin that updates ‘nav’ targets as you scroll a long page.
  • Tab: Toggling for tabbed interfaces.
  • Tooltips: Nifty tooltip plugin.
  • Popover: Extension of tooltip for more extensive popup notes.
  • Alert Messages: A tiny plugin that adds a ‘close’ button to alert message components.
  • Buttons: Allows grouping and toggling of grouped buttons.
  • Collapse: A plugin that gives the traditional ‘accordion’ functionality to a set of layout panels.
  • Carousel: A generic plugin for cycling through a list of contents like images.
  • Typeahead: A simple autocomplete plugin that uses an array as its data source.

Combined with the Components, Plugins and responsive CSS3 based media queries, Twitter Bootstrap offers a potent platform for building nice looking HTML5+Responsive UI web applications quickly.

We will now go through what it takes to build an ASP.NET MVC Application using the Twitter Bootstrap framework and make some tweaks so that it looks ‘cool’ on small devices.

ASP.NET MVC and Twitter Bootstrap

Now that we have got an idea of the capabilities of Twitter Bootstrap, we will see a hands-on of how to integrate Twitter Bootstrap in our ASP.NET application. We will dig deep into the Styles and scripts we use and once done, we will wrap it into a nice Visual Studio project template for future use.

Updating to Twitter Bootstrap

- We start off with an ASP.NET MVC 4 Web Application’s Internet Template. First couple of things to do is to install the Bootstrap package from Nuget and update the jQuery package if its version is less than 1.7.2.

PM> install-package Twitter.Bootstrap

PM> update-package jQuery

- Next we update the BundleConfig.cs class to include the twitter BootStrap scripts and css.

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
bundles.Add(new StyleBundle("~/Content/bootstrapcss").Include(

- We include the newly added bundles to our _Layout.cshtml page and remove the default css bundle (jQuery UI overlaps certain twitter bootstrap styling)


- At the bottom of the page, we add the BootStrap script bundle. It’s important that bootstrap scripts be loaded after the jQuery bundle because it uses jQuery.



- We are all set with the initial setup. Now we’ll go hands on with the layout changes. We are aiming for Twitter Bootstrap’s Responsive UI sample look. Like the ASP.NET default template, it also has a ‘Home’, ‘About’ and ‘Contact’ links and a Login Widget on the top right. The default ASP.NET sample does not have the left hand side list of links, so we’ll ignore it for now.

The following graphic highlights the various CSS classes used. The labels with class definitions only imply

elements. Some of the other elements have been explicitly specified


BootStrap Release 2.1: While this article was in production, BootStrap 2.1 was released. Default Navigation bar is now white in color. However the navbar-inverse class restores the original black Navigation bar. The nuget package for the final release of the article has been updated to BootStrap 2.1.

When we update the _Layout.cshtml, Index.cshtml and _LoginPartial.cshtml to use the above styles, instead of the default styles, our UI comes up as follows and we can see the changes that happen when a browser is resized.



- Now as we can see, the ‘feature’ on the home page is taking up the entire mobile screen space. It seems the ‘hero-unit’ does not respond to media size changes. We can reduce the size of the ‘featured’ section. To do this, we need to update the bootstrap-responsive.css

- We add the required classes in the media section that’s for small smartphone screens and setup sizes appropriately

@media (max-width: 480px)
.hero-unit {
  padding: 5px;
  margin-bottom: 5px;
  background-color: #eeeeee;
  -webkit-border-radius: 3px;
     -moz-border-radius: 3px;
          border-radius: 3px;

.hero-unit h1 {
  margin-bottom: 2px;
  font-size: 20px;
  line-height: 1.2;
  letter-spacing: -1px;
  color: inherit;
.hero-unit h2 {
  margin-bottom: 5px;
  font-size: 14px;
  line-height: 1.2;
  color: inherit;
.hero-unit p {
  font-size: 12px;
  line-height: 1.2;
  font-weight: 200;
  color: inherit;

- When we run our application in a small browser window, it looks as follows


As we see above, now the entire content of the page has fit in the small browser space. This takes care of the home page. Let us update the Registration and Login pages with the Form classes in the bootstrap

- We update the markup of the Register.cshtml as follows. We have removed the

    for all the fields and added the class ‘span3’ for the textboxes. We applied styling for the button and wrapped the registration fields in a div with the class set to “well” as built in component.


            Passwords must be at least
            @Membership.MinRequiredPasswordLength characters long.

    @using (Html.BeginForm())


                Registration Form
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName,
                        new { @class = "span3" })
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email,
                        new { @class = "span3" })
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password,
                        new { @class = "span3" })
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword,
                        new { @class = "span3" })
                                class="btn btn-primary btn-large" />



    - Result of the above change is as follows


    - We update the Login page similarly


    Creating a Visual Studio Project Template

    Now that all the default pages have been updated and we have got a handle of how to use the Bootstrap boilerplate, we would like our MVC projects to start off looking like this without having to go through the exercise of doing all these changes again. Visual Studio provides an easy way to create a Visual Studio project template. Just export it as a template and you are good, you have a neat ASP.NET MVC template that starts off with the Twitter Bootstrap.

    - In Solution Explorer select the Project

    - From File Menu of VS, select “Export Template…


    - Select Project Template and Click Next


    - Next update the details like name and description as required and hit Finish.

    - Start new instance of Visual Studio and select Installed Templates > Visual C#. You will see the newly created Template


    There you have it, your very own project template that creates MVC4 + Twitter Bootstrap based web applications.


    We saw a host of things in this article today, starting with the theory behind Responsive UI and how CSS3 and HTML5 support building of Responsive web UI easily. Next we saw how Media queries worked. We took a look at a well-established boiler plate for Responsive UI design – the Bootstrap, by Twitter. We also saw how to replace default ASP.NET styling with Twitter Bootstrap and finally we created a Project template that can serve as starter MVC projects using Bootstrap.

    Attribution: Some of the images are from BootStrap’s documentation site at licensed under CC 3.0

    Download the entire source code at (GitHub)

    This article has been editorially reviewed by Suprotim Agarwal.

    Absolutely Awesome Book on C# and .NET

    C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

    We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

    Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

    Click here to Explore the Table of Contents or Download Sample Chapters!

    What Others Are Reading!
    Was this article worth reading? Share it with fellow developers too. Thanks!
    Share on LinkedIn
    Share on Google+

    Sumit is a .NET consultant and has been working on Microsoft Technologies since his college days. He edits, he codes and he manages content when at work. C# is his first love, but he is often seen flirting with Java and Objective C. You can follow him on twitter at @sumitkm or email him at sumitkm [at] gmail

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Be Brave on Wednesday, January 30, 2013 3:33 PM
Very informative article Sumit. Well done!
Comment posted by Arnaud on Thursday, February 7, 2013 8:41 AM
I think you should show the source code of the views, because patching HTML code by looking at a screenshot is not very practical! Otherwise it's great article!
Comment posted by Sumit on Thursday, February 14, 2013 8:15 AM
Hi Arnaud,

Images provide minor protection against rampant plagiarism by bot sites, so sorry about the inconvenience.

But, source is two clicks away. Go to the github repo using the link at the end of the article and then they have a big 'Download Zip' button, to download the entire source.
I know GitHub sometimes feels intimidating but the Zip options should help and no registration is required.
Hope this helps,
Comment posted by Ygor Thomaz on Thursday, February 21, 2013 11:11 AM
Ty for your article.

I recommend this video as extension of this article :
Bootstrapping Mvc - Intro To Twitter.Bootstrap.Mvc4

Comment posted by Army on Tuesday, March 26, 2013 3:10 PM
I would say "great article", but there a fundamental CSS styling elements which you neglected to mention. I'm referring to the margin for the hero-unit. Also why not include the source? I realise I can look at GitHub but what a hassle. Other then those issues it's a good read.  
Comment posted by Joel Ransom on Tuesday, April 9, 2013 2:56 PM
Just the sort of article I was looking for, thanks. I will say that the resulting project doesn't include steps you discuss. For instance you say
- Next we update the BundleConfig.cs class to include the twitter BootStrap scripts and css.

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
bundles.Add(new StyleBundle("~/Content/bootstrapcss").Include(

but do something else in the project.

Still, very helpful.
Comment posted by sampath on Saturday, April 20, 2013 11:10 AM
Clean and clear explanation.Keep it up the good job.
Comment posted by Sal on Wednesday, May 29, 2013 4:31 PM
Is there a simple set of code, whether it be a combination of CSS, JavaScript or C# that you can use to dynamically change whatever image is retrieved on a Standard ASPX Page by using the Adaptive Images?
Comment posted by sss4999 on Wednesday, June 19, 2013 9:00 PM
good job. very thanks ;but I can not Download the entire source code at (GitHub) ,so I hope you can send to my mail(
I first user this ,hope you give me more support.
Comment posted by Moi on Thursday, July 11, 2013 2:21 AM
Cool Men! Just staring with ASP.Net
Comment posted by Zhou Broadwell on Tuesday, August 13, 2013 6:01 PM
The bootstrap-responsive.css needs to be included AFTER the bootstrap.css, otherwise the responsive behavior is overwritten.  Also I could not get it working using the *.min.css.  The project included also does not use *.min.css.  The order of the css is correct in the project.
Comment posted by Zhou Broadwell on Wednesday, August 14, 2013 12:55 PM
The bootstrap-responsive.css needs to be included AFTER the bootstrap.css, otherwise the responsive behavior is overwritten.  Also I could not get it working using the *.min.css.  The project included also does not use *.min.css.  The order of the css is correct in the project.
Comment posted by Paul on Tuesday, September 17, 2013 11:14 AM
I upgraded Bootstrap.css to version 3 and my site stopped rendering properly.

I changed the BundleConfig to point at the new Content\Bootstrap folder, but it still had render problems.

Any ideas how to fix this?
Comment posted by Dmitry Efimenko on Monday, October 14, 2013 6:46 PM
People might also find very useful this library of Html helpers for Bootstrap: Nuget ID: TwitterBootstrapMVC. Docs can be found at
Comment posted by Santokh Singh on Friday, October 18, 2013 5:32 AM
Hi Sumit I have been trying to add Jquery mobile with twitter bootstrap in MVC application. have you have any reference for that.
thanks in advance
Comment posted by Sumit on Friday, October 18, 2013 2:41 PM
Santokh, I wouldn't mix jQuery Mobile and BootStrap!
Comment posted by amthenia on Sunday, March 30, 2014 3:05 AM
You will certainly run into the problem with the navbars in Twitter Bootstrap, wanting to increase or decrease them, you can find the solution here:
Comment posted by adrian on Wednesday, November 5, 2014 9:59 AM
What about grids? Sorting individual columns, paging, filter per column, usw.). Any Support from Bootstrap?