Back to: ASP.NET Core Tutorials For Beginners and Professionals
Navigation-Menus in ASP.NET Core MVC Application
In this article, I will discuss How to Create Responsive Navigation-Menus in ASP.NET Core MVC Applications using Bootstrap and jQuery. Please read our previous article discussing the Environment Tag Helper in ASP.NET Core MVC Web Application.
What is Responsive Navigation Menus in ASP.NET Core MVC?
Responsive Navigation Menus are dynamic navigation menus that adapt and respond to different screen sizes and devices used to view the website. They adjust their layout, font sizes, and positioning to provide a consistent user experience across desktops, tablets, and mobile devices. In ASP.NET Core MVC, this can be achieved using front-end frameworks like Bootstrap, which provides built-in support for responsive design, including navigation menus that collapse or adjust based on the screen size.
Why do we need Responsive Navigation Menus in ASP.NET Core MVC?
Responsive Navigation Menus are essential for the following reasons:
- User Experience: With the rise in mobile and tablet usage, ensuring users can easily navigate your site regardless of the device is crucial. Responsive menus improve the site’s usability on mobile devices, making it easy for users to navigate without zooming or scrolling horizontally.
- SEO: Google and other search engines favor mobile-friendly websites. Responsive navigation improves user experience, positively affecting your site’s SEO ranking.
- Efficiency: Instead of creating separate websites for different devices, a responsive menu allows a single website to work across mobile and desktop.
Example to Understand Navigation Menus in ASP.NET Core MVC:
Let us understand this with an example. We want to develop one application, and when we open our web application on large-screen devices like desktops and tablets, we want the navigation menus to look like the image below. Here, the menus List, Create, About, and Contact are visible in a horizontal bar.
But when we open our website on a small screen device like a mobile, we want to show the navigation menus like the one below. Here, you can see the menus List, Create, About, and Contact are not visible; instead, the hamburger menu (three horizontal lines) is visible, and once we click on the three horizontal lines, it will display all the menus.
Let us Proceed and see How we can Implement the above using the ASP.NET Core MVC Application.
Creating a New ASP.NET Core MVC Application:
First, create a new ASP.NET Core Application using the Model-View-Controller Project Template named FirstCoreMVCApplication. Once you have created the project, please ensure Bootstrap and jQuery files are added. By default, these files are automatically added when you create the project using the Model-View-Controller template.
Adding images Folder inside the wwwroot folder:
Add a folder called images with the wwwroot folder and then paste two different images with the names Logo.png and Student.png, as shown in the image below.
Modifying _Layout.cshtml file:
Create your navigation menu using the Bootstrap Navbar component. Bootstrap’s Navbar automatically becomes responsive and toggles between a horizontal menu and a hamburger menu on smaller screens.
Please modify the _Layout.cshtml file, which is present inside the Views => Shared folder, as shown below. In the head section, we refer to the files MyCustomStyleSheet.css, bootstrap.css, query.js, and bootstrap.js. The navbar-toggler button is a responsive component that will appear on smaller screen sizes. When clicked, it toggles the visibility of the navigation menu items.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - FirstCoreMVCApplication</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/FirstCoreMVCApplication.styles.css" asp-append-version="true" /> </head> <body> <!-- Bootstrap container class that provides padding and centers content on the page. --> <div class="container"> <!-- A Bootstrap styled navigation bar, dark-themed. It's set to expand on small devices. --> <nav style="margin-top:15px" class="navbar navbar-expand-sm bg-dark navbar-dark"> <!-- Fluid container for the navbar contents, ensuring proper spacing and alignment. --> <div class="container-fluid"> <!-- A link that acts as the brand logo for the website, navigates to the Home controller's Index action when clicked. The asp-controller and asp-action tags are used for routing in ASP.NET Core MVC. --> <a style="margin-left:5px" class="navbar-brand" asp-controller="home" asp-action="index"> <!-- Displays a logo image with specified width and height. --> <img src="~/images/Logo.png" width="50" height="50"> </a> <!-- Button for toggling the navbar menu on smaller screens (responsive collapse). --> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <!-- Icon for the toggle button, which is the hamburger menu symbol. --> <span class="navbar-toggler-icon"></span> </button> <!-- This section contains the navigation links. Due to the d-sm-inline-flex class, it collapses on small screens and becomes horizontal on larger screens.--> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <!-- Unordered list of navigation links in the navbar, utilizing Bootstrap classes for layout. --> <ul class="navbar-nav flex-grow-1"> <!-- Each list item represents a navigation link to different actions in the Home controller. --> <li class="nav-item"> <!-- Nav link to the Index action in the Home controller, labeled "List". --> <a class="nav-link" asp-controller="home" asp-action="index">List</a> </li> <li class="nav-item"> <!-- Nav link to the Create action in the Home controller, labeled "Create". --> <a class="nav-link" asp-controller="home" asp-action="create">Create</a> </li> <li class="nav-item"> <!-- Nav link to the About action in the Home controller, labeled "About". --> <a class="nav-link" asp-controller="home" asp-action="about">About</a> </li> <li class="nav-item"> <!-- Nav link to the Contact action in the Home controller, labeled "Contact". --> <a class="nav-link" asp-controller="home" asp-action="contact">Contact</a> </li> </ul> </div> </div> </nav> <!-- This is where the content of the page (i.e., the view content) will be rendered. --> <div> @RenderBody() </div> </div> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
Creating Models:
Next, we need to create two enums to store a student’s Gender and Branch. So, create two classes within the Models folder named Gender.cs and Branch.cs. Open the Branch.cs class file and copy and paste the following code. As you can see, we have created the Branch enum with four named constants, i.e., None, CSE, ETC, and Mech.
namespace FirstCoreMVCApplication.Models { public enum Branch { None, CSE, ETC, Mech } }
Next, open the Gender.cs class file and copy and paste the following code. As you can see, we have created the Gender enum with two named constants, i.e., Male and Female.
namespace FirstCoreMVCApplication.Models { public enum Gender { Male, Female } }
Student Model:
We want to display the student information on the web page. So, create a class file named Student.cs within the Models folder and copy and paste the following code.
namespace FirstCoreMVCApplication.Models { public class Student { public int StudentId { get; set; } public string? Name { get; set; } public string? Email { get; set; } public Branch? Branch { get; set; } public Gender? Gender { get; set; } public string? Address { get; set; } } }
Modifying Home Controller:
Next, modify the Home Controller as shown below. As you can see in the code below, we have added two action methods. The Index action method will return all the students, while the Details action takes the student ID and returns that student’s information.
using FirstCoreMVCApplication.Models; using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCApplication.Controllers { public class HomeController : Controller { //Create a Variable to Hold List of Students //This is going to be our data source private List<Student> listStudents = new List<Student>(); public HomeController() { //Within the Constructor we are Initializing listStudents variable //In Real-Time, we will get the data from the database listStudents = new List<Student>() { new Student() { StudentId = 101, Name = "James", Branch = Branch.CSE, Gender = Gender.Male, Address = "A1-2018", Email = "James@g.com" }, new Student() { StudentId = 102, Name = "Priyanka", Branch = Branch.ETC, Gender = Gender.Female, Address = "A1-2019", Email = "Priyanka@g.com" }, new Student() { StudentId = 103, Name = "David", Branch = Branch.CSE, Gender = Gender.Male, Address = "A1-2020", Email = "David@g.com" }, new Student() { StudentId = 104, Name = "Pranaya", Branch = Branch.Mech, Gender = Gender.Male, Address = "A1-2021", Email = "Pranaya@g.com" } }; } public ViewResult Index() { //returning all the students return View(listStudents); } public ViewResult Details(int Id) { //returning the student based on the Student Id var studentDetails = listStudents.FirstOrDefault(std => std.StudentId == Id); return View(studentDetails); } } }
Modifying Index.cshtml file:
Please modify the Index view, which is present inside the Home folder, as shown below. Notice how the buttons (View, Edit, and Delete) are attached to each other. Use the Bootstrap margin classes (m-1, m-2, etc.) to include the margin between these buttons. In the class name, “m” stands for margin, and the numbers 1, 2, 3, etc., are the size of the space you want between the buttons. In this view, List<Student> is the model, and using a for each loop, we are accessing all the students. Further, if you notice, we have used Tag Helper to generate the link for the View button.
@model List<Student> @{ ViewBag.Title = "Student List"; Layout = "~/Views/Shared/_Layout.cshtml"; } <!-- Bootstrap's row class to create a horizontal group of columns. --> <div class="row"> <!-- Loops through each student in the model (a List of Student objects) and renders a Bootstrap card for each student. --> @foreach (var student in Model) { <!-- Defines a Bootstrap column with a size of 3 out of 12 columns (25% width on small screens and above). --> <div class="col-sm-3"> <!-- Creates a Bootstrap card with margin (m-3) to separate it from other elements. --> <div class="card m-3"> <!-- Card header to display the student's name, wrapped inside an <h3> tag. --> <div class="card-header"> <h3>@student.Name</h3> <!-- Displays the Name property of the current student. --> </div> <!-- Card body to display the student's image. --> <div class="card-body"> <!-- Renders a placeholder student image inside the card. The image source is static and points to "Student.png" in the images folder. --> <img class="card-img-top" src="~/images/Student.png" /> </div> <!-- Card footer to display action buttons aligned at the center of the card. --> <div class="card-footer text-center"> <!-- Creates a button link to the Details action in the Home controller, passing the student's ID as a route parameter. --> <a asp-controller="Home" asp-action="Details" asp-route-id="@student.StudentId" class="btn btn-primary m-1">View</a> <!-- 'View' button with primary styling. --> <!-- Static button for editing (not functional in this example). --> <a href="#" class="btn btn-primary m-1">Edit</a> <!-- 'Edit' button with primary styling. --> <!-- Static button for deleting (not functional in this example). --> <a href="#" class="btn btn-danger m-1">Delete</a> <!-- 'Delete' button with danger (red) styling. --> </div> </div> </div> } </div>
Creating Detail.cshtml file:
Please create a view named Details.cshtml within the Views/Home folder and copy and paste the following code into it. In this view, the Student will be the model, and we can access the student model properties using the @Model object.
@model Student @{ ViewBag.Title = "Student Details"; Layout = "~/Views/Shared/_Layout.cshtml"; } <!-- Main container for the content of the page, using Bootstrap's container class and margin-top utility (mt-5) for spacing. --> <div class="container mt-5"> <!-- A Bootstrap row with centered content using justify-content-center, aligning items horizontally in the center. --> <div class="row justify-content-center"> <!-- Defines a responsive column that is 6/12 (half) on large screens and 8/12 on medium screens, keeping the content properly sized. --> <div class="col-lg-6 col-md-8"> <!-- A Bootstrap card component with a shadow effect, creating a modern, elevated look. --> <div class="card shadow"> <!-- Card header section with a primary background color and white text, used for displaying the student's name. --> <div class="card-header bg-primary text-white"> <!-- The student's name is displayed as a heading. The 'my-2' class adds vertical margin to the heading. --> <h2 class="my-2">@Model?.Name</h2> <!-- The safe navigation operator (?) ensures the model is checked for null before accessing properties. --> </div> <!-- Card body where the student's details are displayed, including a photo and their information. --> <div class="card-body text-center"> <!-- Displays the student's image with 100% width (but constrained to a maximum of 300px), centered using auto margins. --> <img class="card-img mb-3" src="~/images/Student.png" alt="Student Photo" style="width: 100%; max-width: 300px; height: auto; margin: 0 auto;"> <!-- Displays various details of the student using <h5> tags for the Student ID, Email, Branch, Gender, and Address. --> <h5 class="card-title">Student ID: @Model?.StudentId</h5> <!-- Safely accesses the StudentId property of the model. --> <h5 class="card-title">Email: @Model?.Email</h5> <!-- Displays the student's email. --> <h5 class="card-title">Branch: @Model?.Branch</h5> <!-- Displays the student's branch. --> <h5 class="card-title">Gender: @Model?.Gender</h5> <!-- Displays the student's gender. --> <h5 class="card-title">Address: @Model?.Address</h5> <!-- Displays the student's address. --> </div> <!-- Card footer with transparent background, containing a group of buttons. --> <div class="card-footer bg-transparent"> <!-- Bootstrap button group to align the buttons in a horizontal group. --> <div class="btn-group" role="group"> <!-- Back button (currently a placeholder link) with secondary styling (gray button). --> <a href="#" class="btn btn-secondary">Back</a> <!-- Edit button with info styling (blue button). --> <a href="#" class="btn btn-info">Edit</a> <!-- Delete button with danger styling (red button). --> <a href="#" class="btn btn-danger">Delete</a> </div> </div> </div> </div> </div> </div>
Now, run your application and resize the browser window, or use a mobile device to see the responsive navigation menu in action. On smaller screens, the menu items should collapse into a hamburger menu (three horizontal lines). When you click the hamburger menu, the menu items will appear in a dropdown.
In the next article, I will discuss Form Tag Helpers in an ASP.NET Core MVC Application with Examples. In this article, I explain how to create Responsive Navigation Menus in an ASP.NET Core MVC Application using Bootstrap with Examples. I hope you enjoy this article.
Hello,
i tried this implementing but facing small issue. I followed all steps ui is coming correctly but anchore tag helper not rendering its showing as taghelper.
i modified removing ; in _ViewImports.cshtml then tag helpers working properly. but UI is not working properly.
@using AspNetCore_Menu.Models
@using AspNetCore_Menu.Models.DataTypes
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
if ; is kept for each like @using AspNetCore_Menu.Models; then ui is properly coming.
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseMvcWithDefaultRoute();
}
Any suggestions.
and thanks for nice article its easy to understand.
Can you update the page to include the img files you referred to (Logo.png and Student.png)? For adding bootstrap and JQuery files, is it the same as adding the client package of twitter-bootstrap you mentioned earlier? Thanks.