Tech Junkie Blog - Real World Tutorials, Happy Coding!: End-to-End ASP.NET MVC: Create A Responsive Layout With Bootstrap

Thursday, June 4, 2015

End-to-End ASP.NET MVC: Create A Responsive Layout With Bootstrap

In our previous blog we created a simple _Layout.cshtml file that does not have any markup just to make things simple.  In this blog we will use Bootstrap to make the layout look more professional and responsive, so that it can be viewed in any screen size.  The previous layout looks like screenshot below.

















The Bootstrap version will look like the screenshot below.














Step-By-Step Instructions:

1.  Open the NorthwindCafe project
2. Open the BundleConfig.cs file in the App_Start folder and type in the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace NorthwindCafe.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery", "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js").Include("~/Scripts/jquery-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/bootstrap", "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js").Include("~/Scripts/bootstrap.js", "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/bootstrap", "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css").Include("~/Content/bootstrap.css"));

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/Styles.css"));

            BundleTable.EnableOptimizations = true;
            bundles.UseCdn = true;
        }
    }
}

The code above creates a new StyleBundle with the virtual path ~/Content/bootstrap, which is created specifically for the bootstrap css files. Then we change the StyleBundle("~/Content/css") bundle to contain stylesheets that are site specific. We will add the Styles.css file later

 3.  Now we are ready to add the header navigation to the _Layout.cshtml file, which is the layout specified as the default layout in the _ViewStart.cshtml file.

4.  Open the _Layout.cshtml file, then type in the following code

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>@Page.Title</title>
        @RenderSection("head", required: false)
        @Styles.Render("~/Content/bootstrap")
        @Styles.Render("~/Content/css")
    </head>

The code above defines the viewpoint as the device-width, a viewport is the width of the screen used to determine how bootstrap will display the elements on the screen. The device-width viewport means that the elements will be render to the screen's device width. The rest of the code just renders all the style bundles that we've defined in the BundleConfig.cs file.

5.  Once we have the head section defined we can define the header section of the layout.

    
<header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto font-weight-bold">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">About</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Contact</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                           data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Products
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Beverages</a>
                            <a class="dropdown-item" href="#">Condiments</a>
                            <a class="dropdown-item" href="#">Confections</a>
                            <a class="dropdown-item" href="#">Dairy Products</a>
                            <a class="dropdown-item" href="#">Grains/Cereals</a>
                            <a class="dropdown-item" href="#">Meat/Poultry</a>
                            <a class="dropdown-item" href="#">Produce</a>
                            <a class="dropdown-item" href="#">Seafood</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="jumbotron" id="header-jumbotron">
            <h2>Northwind Store</h2>
        </div>
    </header>

The code above looks complicated, but it's not that complicated. First we use the bootstrap class "navbar navbar-default navbar-fixed-top" to tell the browser that we want the navbar that fixes on the top of the screen even when the user scrolls. All we have to do is define the class and bootstrap does the rest for us.  The navbar class defines the top navigation of the layout like the screenshot below





6.  The following section defines the menu when the screen gets really small and the elements have to be stacked because it does not have the width to display everything horizontally.

                          
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

The menu looks like the following when the screen gets really small






























7.  Now we want to define the actual navigation bar, type in the following code to define the "Home", "About","Contact" tabs, and the "Products" drop down.
 
<body>
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto font-weight-bold">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">About</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Contact</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                           data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Products
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Beverages</a>
                            <a class="dropdown-item" href="#">Condiments</a>
                            <a class="dropdown-item" href="#">Confections</a>
                            <a class="dropdown-item" href="#">Dairy Products</a>
                            <a class="dropdown-item" href="#">Grains/Cereals</a>
                            <a class="dropdown-item" href="#">Meat/Poultry</a>
                            <a class="dropdown-item" href="#">Produce</a>
                            <a class="dropdown-item" href="#">Seafood</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="jumbotron" id="header-jumbotron">
            <h2>Northwind Store</h2>
        </div>
    </header>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</body>

Like everything else in bootstrap we just have to call class "navbar-collapse collapse" and nest the div with the <ul> element with class "nav navbar-nav" and bootstrap picks it up applies the stylesheets and functionalities automatically. That's the great thing about bootstrap. It makes things easy, but the bad thing is a lot of the sites nowadays have the same bootstrapy look and feel to them. But it's great if you want to throw something together quickly and make it look decent.

So the code below defines the "Home", "About", and "Contact" tab
 
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto font-weight-bold">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">About</a>
                    </li>
                    <li class="nav-item">

And the following code defines the "Products" dropdown menu.
                                    
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                           data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Products
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Beverages</a>
                            <a class="dropdown-item" href="#">Condiments</a>
                            <a class="dropdown-item" href="#">Confections</a>
                            <a class="dropdown-item" href="#">Dairy Products</a>
                            <a class="dropdown-item" href="#">Grains/Cereals</a>
                            <a class="dropdown-item" href="#">Meat/Poultry</a>
                            <a class="dropdown-item" href="#">Produce</a>
                            <a class="dropdown-item" href="#">Seafood</a>
                        </div>
                    </li>

8. Now we want to add a jumbotron to make the navigation stand out a little bit.

           <div class="jumbotron" id="header-jumbotron">
                        <h2>Northwind Store</h2>
            </div>

The code above produces the following output










9.  To style the jumbotron we have to create our own stylesheet so that it does not interfere with the default bootstrap styles.  So create a new css file in the ~/Content folder and give it the name Styles.css.

10.  In the Styles.css file type the following code

body {
}

#header-jumbotron{
    background-color: #6f5499;
}
#navbar {
    margin-left: 50px;
}

#header-jumbotron h2{
    margin-left: 40px;
    color: #fff;
    margin-top: 50px;
}


The code above defines the margin for the navbar and the jumbotron, it also set the text color and background color for the jumbotron.

11. Now we want to wrap things up by calling the script bundles at the bottom of the page

        
        @RenderBody()
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")

12. The complete code for the _Layout.cshtml file is the following

<!DOCTYPE html>
<html>
<head>
    <title>@Page.Title</title>
    @RenderSection("head", required: false)
    @Styles.Render("~/Content/bootstrap")
    @Styles.Render("~/Content/css")
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto font-weight-bold">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">About</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Contact</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                           data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Products
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Beverages</a>
                            <a class="dropdown-item" href="#">Condiments</a>
                            <a class="dropdown-item" href="#">Confections</a>
                            <a class="dropdown-item" href="#">Dairy Products</a>
                            <a class="dropdown-item" href="#">Grains/Cereals</a>
                            <a class="dropdown-item" href="#">Meat/Poultry</a>
                            <a class="dropdown-item" href="#">Produce</a>
                            <a class="dropdown-item" href="#">Seafood</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="jumbotron" id="header-jumbotron">
            <h2>Northwind Store</h2>
        </div>
    </header>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</body>
</html>


Similar Posts:

14 comments:

  1. For some reason, this line in the BundleConfig.cs file is breaking the responsive navigation.
    bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/Styles.css"));

    If I comment it out, it works but I really need to add custom styles.

    ReplyDelete
    Replies
    1. Add below code in _Layout.cshtml under header tag :
      @Styles.Render("~/Content/myStyle")

      Also this line of code in BundleConfig.cs :
      bundles.Add(new StyleBundle("~/Content/mystyle").Include("~/Content/Styles.css"));

      Hope it will help!

      Delete
    2. Add below code in _Layout.cshtml under header tag :
      @Styles.Render("~/Content/myStyle")

      Also this line of code in BundleConfig.cs :
      bundles.Add(new StyleBundle("~/Content/mystyle").Include("~/Content/Styles.css"));

      Hope it will help!

      Delete
  2. Stephanie, I am running the guide just as you are and am coming across the same problem. This is a fantastic guide but, maybe it is becoming dated? Still learning of course but, I am just going to continue without this functionality.

    ReplyDelete
  3. I am having the same problem

    ReplyDelete
    Replies
    1. Add below code in _Layout.cshtml under header tag :
      @Styles.Render("~/Content/myStyle")

      Also this line of code in BundleConfig.cs :
      bundles.Add(new StyleBundle("~/Content/mystyle").Include("~/Content/Styles.css"));

      Hope it will help!

      Delete
    2. I am glad the users are helping each other. As I've mentioned before, I have a daytime job. So I don't have time to maintain this blog. My goal for this blog is to spark you interest in coding and web development. I am really impressed with the self-help. I never claimed to be an expert. I just hope I had more time to answer your questions. Keep up with the community help. I encourage it. What I say is not the authority. That's the fun of software development. It's wide open. It's a craft. Its not just about the money.

      Delete
  4. remove the error code and add the style sheer seperately @Styles.Render("~/Content/mynewstyle.css")

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. my @Scripts.Render and @Styles.Render are both underlined red. why is that? how do i get rid of it?

    ReplyDelete
  7. LEGIT FULLZ & TOOLS STORE

    Hello to All !

    We are offering all types of tools & Fullz on discounted price.
    If you are in search of anything regarding fullz, tools, tutorials, Hack Pack, etc
    Feel Free to contact

    ***CONTACT 24/7***
    **Telegram > @leadsupplier
    **ICQ > 752822040
    **Skype > Peeterhacks
    **Wicker me > peeterhacks

    "SSN LEADS/FULLZ AVAILABLE"
    "TOOLS & TUTORIALS AVAILABLE FOR HACKING, SPAMMING,
    CARDING, CASHOUT, CLONING, SCRIPTING ETC"

    **************************************
    "Fresh Spammed SSN Fullz info included"
    >>SSN FULLZ with complete info
    >>CC With CVV (vbv & non vbv) Fullz USA
    >>FULLZ FOR SBA, PUA & TAX RETURN FILLING
    >>USA I.D Photos Front & Back
    >>High Credit Score fullz (700+ Scores)
    >>DL number, Employee Details, Bank Details Included
    >>Complete Premium Info with Relative Info

    ***************************************
    COMPLETE GUIDE FOR TUTORIALS & TOOLS

    "SPAMMING" "HACKING" "CARDING" "CASH OUT"
    "KALI LINUX" "BLOCKCHAIN BLUE PRINTS" "SCRIPTING"
    "FRAUD BIBLE"

    "TOOLS & TUTORIALS LIST"
    =>Ethical Hacking Ebooks, Tools & Tutorials
    =>Bitcoin Hacking
    =>Kali Linux
    =>Fraud Bible
    =>RAT
    =>Keylogger & Keystroke Logger
    =>WhatsApp Hacking & Hacked Version of WhatsApp
    =>Facebook & Google Hacking
    =>Bitcoin Flasher
    =>SQL Injector
    =>Premium Logs (PayPal/Amazon/Coinbase/Netflix/FedEx/Banks)
    =>Bitcoin Cracker
    =>SMTP Linux Root
    =>Shell Scripting
    =>DUMPS with pins track 1 and 2 with & without pin
    =>SMTP's, Safe Socks, Rdp's brute
    =>PHP mailer
    =>SMS Sender & Email Blaster
    =>Cpanel
    =>Server I.P's & Proxies
    =>Viruses & VPN's
    =>HQ Email Combo (Gmail, Yahoo, Hotmail, MSN, AOL, etc.)

    *Serious buyers will always welcome
    *Price will be reduce in bulk order
    *Discount offers will give to serious buyers
    *Hope we do a great business together

    ===>Contact 24/7<===
    ==>Telegram > @leadsupplier
    ==>ICQ > 752822040
    ==>Skype > Peeterhacks
    ==>Wicker me > peeterhacks

    ReplyDelete
  8. If You Come from a Low-Income Family and You Need a Free Tablet for Other Reasons, You Will Not Worry. Apply for Assurance Wireless Tablet Through the Line Line Assistance Program. Assurance Wireless Free Tablet Program Can Get a Free Tablet for Low-Income People.
    Free Gas Card Online

    ReplyDelete

Search This Blog