Skip to main content

Building Responsive UI with Twitter Bootstrap and MVC4

ASP.NET MVC
The Model-View-Controller (MVC) design pattern is an architectural design pattern for any standard development that separates the components of an application. This allows applications to handle very flexible and extensible and easy to handle.
The MVC model defines web applications with 3 logic layers: i.e. the business layer (Model logic), the display layer (View logic), and the input control (Controller logic). Check more details and you can also see a working MVC sample.

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. Unlike most front-end frameworks, Bootstrap is interesting because, in addition to it being a full-featured CSS framework, it adds JavaScript plugins (jQuery plugins are in the bootstrap.js file), typography, HTML scaffolding, and components. Combined with the Plugins and responsive CSS3-based media queries; Twitter Bootstrap offers a potent platform for building nice-looking HTML5+Responsive UI web applications in no time J

Integrate Twitter Bootstrap with ASP.NET MVC
Now that we have got an idea of the Twitter Bootstrap and MVC, we will see a hands-on of how to integrate Twitter Bootstrap into our ASP.NET MVC application.

Select New -> Project -> Select ASP.NET MVC 4 Web Application (Under Web template) -> and provide your project and solution a name.


Click OK and Select the Internet Application template from the next window (you can also select any other template if you want) and click OK.


Our default MVC4 application is ready to use and this application by default supports responsive design and based on the screen size it’ll automatically adjust the content of the application. But Microsoft is not so good with front-end UI development. Run the application and check the default application in the browser.

                           
Add bootstrap to your widget from NuGet package manager - > Right Click on Application and select Manage NuGet Packages.

In the Manage NuGet Packages screen, select Online from the left panel, Then NuGet official Package source underneath, and search for Bootstrap MVC. From the search result list, select Bootstrap for MVC 4 and click on Install.


Once the installation process completes, look at the Content folder and the Script folder in the solution. The bootstrap CSS and script files will be available.


Also, there is a new class BootstrapBundleConfig under the App_Start folder. This class contains the following code and is used to bundle Bootstrap Script and CSS files.

using System.Web.Optimization;
[assembly: WebActivatorEx.PostApplicationStartMethod(
typeof(MVCAppWithBootstrap.App_Start.BootstrapBundleConfig)
, "RegisterBundles")]
namespace MVCAppWithBootstrap.App_Start
{
       public class BootstrapBundleConfig
       {
              public static void RegisterBundles()
              {
                     // Add @Styles.Render("~/Content/bootstrap")
in the <head/> of your    _Layout.cshtml view
                     // Add @Scripts.Render("~/bundles/bootstrap")
after jQuery in your _Layout.cshtml view
                     // When <compilation debug="true" />, MVC4 will render
the full readable version. When set to <compilation debug="false" />,
the minified version will be rendered automatically
                    BundleTable.Bundles.Add(
                new ScriptBundle("~/bundles/bootstrap")
                .Include("~/Scripts/bootstrap*"));
                     BundleTable.Bundles.Add(
                new StyleBundle("~/Content/bootstrap")
                .Include("~/Content/bootstrap.css",
                "~/Content/bootstrap-responsive.css"));
              }
       }
}

Now replace everything in _Layout.cshtml (under Views/Shared folder) with the following code (updated with bootstrap CSS):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/bootstrap")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @helper ActiveLink(string actionName, string controllerName, string areaName)
    {
        if (ViewContext.RouteData.Values["action"].ToString() == actionName &&
                ViewContext.RouteData.Values["controller"].ToString() == controllerName &&
                (ViewContext.RouteData.DataTokens["area"] == null
                || ViewContext.RouteData.DataTokens["area"].ToString() == areaName))
        {
            @:active
        }
    }
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="navbar-inner">
            <div class="container">
                <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="brand" href="/">Bootstrap MVC Application</a>
                <div class="nav-collapse collapse">
                    <ul class="nav">
                        <li class="@ActiveLink("Index", "Home", null)">@Html.ActionLink("Home", "Index", "Home")</li>
                        <li class="@ActiveLink("About", "Home", null)">@Html.ActionLink("About", "About", "Home")</li>
                        <li class="@ActiveLink("Contact", "Home", null)">@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        @RenderSection("featured", required: false)
        @RenderBody()
        <hr />
        <div class="footer">
            <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
        </div>
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </div>
</body>
</html>

You’ll note that we have included bootstrap CSS (under the “head” section), and bootstrap scripts (in the “body” section), remaining code is almost identical with some style changes, but we have also included one ActiveLink helper method to show selected status of navigation links.

And replace Index.cshtml (under Views/ Home folder) with the following code (updated with bootstrap CSS):

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <div class="hero-unit">
        <h1>@ViewBag.Title.</h1>
        <h2>@ViewBag.Message</h2>
        <p>
            To learn more about ASP.NET MVC visit
            <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
            The page features <mark>videos, tutorials, and samples</mark>
            to help you get the most from ASP.NET MVC.
            If you have any questions about ASP.NET MVC visit
        </p>
        <a class="btn btn-large btn-success" href="http://forums.asp.net/1146.aspx/1?MVC"
            title="ASP.NET MVC Forum">our forums</a>.
    </div>
}
<!-- Example row of columns -->
<div class="row-fluid">
    <div class="span4">
        <h2>Getting Started</h2>
        ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
        enables a clean separation of concerns and that gives you full control over markup
        for enjoyable, agile development. ASP.NET MVC includes many features that enable
        fast, TDD-friendly development for creating sophisticated applications that use
        the latest web standards.
    <p>
        <a class="btn" href="http://go.microsoft.com/fwlink/?LinkId=245151">Learn more &raquo;</a>
    </p>
    </div>
    <div class="span4">
        <h2>Add NuGet packages and jump-start your coding</h2>
        <p>NuGet makes it easy to install and update free libraries and tools.</p>
        <p>
            <a class="btn" href="http://go.microsoft.com/fwlink/?LinkId=245153">Learn more &raquo;</a>
        </p>
    </div>
    <div class="span4">
        <h2>Find Web Hosting</h2>
        <p>
            You can easily find a web hosting company that offers the right mix of features
            and price for your applications.
        </p>
        <p>
            <a class="btn" href="http://go.microsoft.com/fwlink/?LinkId=245157">Learn more &raquo;</a>
        </p>
    </div>
</div>

So we have set up our MVC master view and home view with bootstrap and also set up other views with bootstrap classes as per your convenience.

Now run the application and see the bootstrap with the MVC application in action:


Let’s have a look at how this application will be seen on small screens (i.e. on tablets, mobiles, etc.).


That’s it for the day guys, you can download and see a working sample J

Comments

  1. Very good Description

    ReplyDelete
  2. Nice article . Thanks . You said replace code in _layout.cshtml but you have protected page from copying text :)

    ReplyDelete
  3. Very Nice Explanation. Sandeep

    Thanks..

    ReplyDelete

Post a Comment

Popular posts from this blog

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...