• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Saturday, September 5, 2020

How to Use Bootstrap in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss How to Use Bootstrap in ASP.NET Core MVC Application. Please read our previous article before proceeding to this article where we discussed the How to Installed Bootstrap in ASP.NET Core MVC Application using Library Manager (Libman). Here, I will discuss how to use bootstrap as well as how to create and use custom CSS in a view.

Creating a Custom Style Sheet in ASP.NET Core MVC Application:
First, create a folder with the name CSS within the wwwroot folder. All the custom CSS files are going to be created within this folder. Once you create the CSS folder, let’s add a CSS file with the name MyCustomStyleSheet.css.

To create a style sheet, right-click on the CSS folder and then select “Add – New Item” from the context menu. Then search for CSS and select Style Sheet, provide a meaningful name and finally click on the Add button as shown in the below image.
Creating a Custom Style Sheet in ASP.NET Core MVC Application

Once you add the MyCustomStyleSheet.css file, then your wwwroot folder should looks as shown below.
How to Use Bootstrap in ASP.NET Core MVC Application

Note: All the site custom CSS needs to be placed within the MyCustomStyleSheet.css file. So, open the MyCustomStyleSheet.css file and copy and paste the following code in it.
.btn {
     width: 80px;
}
How to Using Bootstrap in ASP.NET Core MVC Application?
In order to use bootstrap, first, you need to include a reference to the bootstrap.css file. You can add the reference in each individual views. But as we are going to use the Layout file, so we are going to add a reference to the bootstrap.css file in the _Layout.css file. Along with bootstrap.css, we are also including a reference to our custom style sheet i.e. MyCustomStyleSheet.css.

Modifying the _Layout.cshtm file:
Please modify the Layout file which is present in the shared folder as shown below.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
<link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
    <link href="~/css/MyCustomStyleSheet.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        @RenderBody()
    </div>
</body>
</html>
As you can see in the HTML code, we have included references for both bootstrap.css as well as MyCustomStyleSheet.css files. Here, we are also using the bootstrap container class for positioning the elements on the page.

Creating Models:
Within the Models folder, add a class file with the name Student.cs and then copy and paste the following code in it.
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}
Modifying the Home Controller:
Please modify the Home Controller as shown below.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            List<Student> listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
               new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
               new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };
            return View(listStudents);
        }
        public ViewResult Details(int Id)
        {
            var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" };
            return View(studentDetails);
        }
    }
}
Modifying the Startup class:
Please modify the Startup class as shown below. Here, to serve the bootstrap we need to add the static files middle layer before the MVC middle layer in the request processing pipeline.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace FirstCoreMVCApplication
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //Adding Static Files Middleware to serve the static files
            app.UseStaticFiles();
            //Adding MVC Middleware
            app.UseMvcWithDefaultRoute();
        }
    }
}
Modifying the Index view:
Please modify the Index view of Home Controller as shown below.
@model List<FirstCoreMVCApplication.Models.Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>View</th>
                <th>Update</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.StudentId</td>
                    <td>@student.Name</td>
                    <td class="text-center">View</td>
                    <td class="text-center">Edit</td>
                    <td class="text-center">Delete</td>
                </tr>
            }
        </tbody>
    </table>
</div>
Modifying the Details View:
Please modify the Details view as shown below.
@model FirstCoreMVCApplication.Models.Student
@{
    ViewBag.Title = "Student Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row justify-content-center m-3">
    <div class="col-sm-8">
        <div class="card">
            <div class="card-header text-center">
                <h1>@Model.Name</h1>
            </div>
            <div class="card-body text-center">
                <h4>Studnet ID : @Model.StudentId</h4>
                <h4>Branch : @Model.Branch</h4>
                <h4>Section : @Model.Section</h4>
                <h4>Gender : @Model.Gender</h4>
            </div>
            <div class="card-footer text-center">
                <a href="#" class="btn btn-primary">Back</a>
                <a href="#" class="btn btn-primary">Edit</a>
                <a href="#" class="btn btn-danger">Delete</a>
            </div>
        </div>
    </div>
</div>
That’s it. Save the changes and run the application and see the output as expected. Here, we have just created the View, Update, Delete, Back buttons but not implemented. In our upcoming articles, I will show you how to implement the CRUD operation in ASP.NET Core MVC Application.

In the next article, I am going to discuss the Tag Helpers in ASP.NET Core MVC Application. Here, in this article, I try to explain How to Use Bootstrap in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand How to Use Bootstrap in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to Install Bootstrap in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     1 comment   

In this article, I am going to discuss How to Install Bootstrap in ASP.NET Core MVC Application. Please read our previous article, where we discussed the ViewImports in ASP.NET Core MVC Application. As part of this article, I am going to discuss the following pointers.
  1. Different Tools to Install Client-Side Packages in ASP.NET Core.
  2. What is Library Manager or Libman in ASP.NET Core?
  3. How to Check and Upgrade the Version in Visual Studio?
  4. How to Install Bootstrap in ASP.NET Core Using Library Manager?
  5. What is the libman.json file in ASP.NET Core?
  6. How to Clean and Restore Client-Side Libraries using Libman in ASP.NET Core?
  7. How to uninstall or update a Client-Side Library using the libman.json file?
Different Tools to Install Client-Side Packages in ASP.NET Core:
There are many tools available that you can use to install client-side packages such as JQuery and Bootstrap using Visual Studio. Some of the popular tools are as follows/;
  1. Bower
  2. NPM
  3. WebPack, etc.
But here in this article, I am not going to use any of the above tools instead we are going to use Library Manager which is known as Libman to install the client-side packages. In our upcoming article, I will show you how to use Bower, NPM, and WrebPack to install the client-side packages.

What is Library Manager or Libman in ASP.NET Core?
The Library Manager or LinMan is one of the most popular light-weight, client-side library acquisition tool. This tool is basically used to download the client-side libraries and frameworks such as Bootstrap and JQuery from a file system or from a CDN (Content Delivery Network). In order to use the Library Manager, you should have Visual Studio 2017 version 15.8 or later.

How to Check and Upgrade the Version in Visual Studio?
In order to check the Visual Studio Version, you need to follow the below steps.

Click on the “Help” menu and then select the “About Microsoft Visual Studio” option from the context menu. This will open the “About Microsoft Visual Studio” window which shows the version number of Visual Studio as shown in the below image. On my machine, I have installed 15.9.5.
How to Check and Upgrade the Version in Visual Studio

If you have installed an older version of Visual Studio 2017, then you can easily update it. In order to update the version of visual studio, you need to follow the below steps.

Click on the “Help” menu and then select the “Check for Updates” option from the context menu. The window appears will display the current version as well as the latest version available of visual studio. Then you need to click on the “Update” button as shown in the below image which will update your visual studio 2017 to its latest version.
Update Visual Studio 2017 to its Latest Version

How to Install Bootstrap in ASP.NET Core Using Library Manager?
You need to follow the below steps to install Bootstrap in ASP.NET Core MVC Application using the Library Manager (Libman).
  1. Right-click on the “Project Name” in the Solution Explorer and then select “Add > Client-Side Library” which will open the “Add Client-Side Library” window.
  2. Leave the default provider as it is which “cdnjs” is in this case. The other providers are filesystem and unpkg.
  3. In the “Library” text box, just type “twitter-bootstrap“. You can also get intelligence support once you start typing. Once you select the matching entry, then it tries to install the latest version of bootstrap. However, if you want then you can also type the version manually you want. Here, we are installing the latest version of Bootstrap i.e. (“twitter-bootstrap@4.3.1”).
  4. There are two radio buttons to select whether you include “All library files” or “Choose Specific files“. If you select the “All library files” radio button then all the files are going to be downloaded. On the other hand, if you select the “Choose Specific files” radio button then you need to check the selected checkboxes as per your requirement. Here I am selecting the “All library files” radio button.
  5. In the “Target Location” text box specify the folder location where you want the library files to be installed. By default, the static files are only served from the wwwroot folder. Here, I am going with the default location i.e. “wwwroot/lib/twitter-bootstrap/”.
  6. Finally, click on the “Install” button as shown in the image below.
How to Install Bootstrap in ASP.NET Core Using Library Manager

Once it successfully installed, then you will find two things. One is the libman.json file and the second one the required bootstrap files. Please have a look at the following image.
Installing Bootstrap in asp.net Core MVC

What is the libman.json file in ASP.NET Core?
The libman.json file is the Library Manager manifest file. You will find the following code in the libman.json file.
libman.json file in ASP.NET Core

As you can see in the above image, we have an entry for the Bootstrap library that we just installed using the Libman. It is also possible to install the client-side libraries like bootstrap and JQuery by editing the above manifest file.

How to clean Client-Side Libraries using Libman in ASP.NET Core?
If you want to clean the library files which are created by using the Library Manager, then you just need to right-click on the libman.json file and then select the “Clean Client-Side Libraries” option from the context menu. Once you click on the “Clean Client-Side Libraries” option then it will delete all the library files from the respective destination folder. The point that you need to keep in mind is, it will only delete the files from the folder but not in the libman.json file.

How to Restore Client-Side Libraries using Libman in ASP.NET Core?
If you want to restore the deleted files, then you just need to right-click on the libman.json file and then select the “Restore Client-Side Libraries” option from the context menu. This will again download and installed the required library files into the specified destination folder.
Clean and Restore client-side packages using Libman

How to uninstall or update a Client-Side Library using the libman.json file?
If you want to uninstall or update a client-side library using the libman.json file, then you need to follow the below steps.
  1. Open the libman.json file
  2. Click on the client-side library which you want to uninstall or update
  3. A light bulb icon will appear at the left side
  4. Click on the light bulb icon and then you will see the options whether to update or uninstall that specific client-side library as shown in the below image.
uninstall or update a Client-Side Library using libman.json file

Another approach to uninstall a client-side library is to remove the entry in the libman.json file and upon saving the file the respective client-side libraries are uninstalled from the respective folder location.

Another approach to upgrade or downgrade a client-side library is to change the version number directly in the libman.json file and upon saving the file the respective client-side library will be updated to the version you modified.

Note: While updating the version number, you will also get the visual studio intelligence as shown in the below image.
Visual Studio Intellisense in Libman file

In the next article, I am going to discuss how to use Bootstrap in ASP.NET Core MVC Application. Here, in this article, I try to explain How to Install Bootstrap in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand How to Install Bootstrap in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

ViewImports in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the ViewImports in ASP.NET Core MVC Application. Please read our previous article before proceeding to this article as it is a continuation part of our previous article where we discussed the ViewStart in Layout Page in ASP.NET Core MVC Application. The ASP.NET Core MVC and Razor comes with a lot of new advanced features for working with the Razor views. ViewImports is one of the new features. As part of this article, we are going to discuss the following pointers.
  1. What is _ViewImports.cshtml?
  2. Understanding ViewImports with an example.
  3. Creating ViewImports.cshtml file in ASP.NET Core MVC Application.
  4. Understanding the hierarchical Order of ViewImports file in ASP.NET Core MVC.
What is _ViewImports.cshtml in ASP.NET Core MVC Application?
In ASP.NET Core MVC Application, the _ViewImports.cshtml file provides a mechanism to include the directives globally for Razor Pages so that we don’t have to add them individually in each and every page. As of this article, the _ViewImports.cshtml file supports the following directives:
  1. @addTagHelper
  2. @tagHelperPrefix
  3. @removeTagHelper
  4. @namespace
  5. @inject
  6. @model
  7. @using
The @addTagHelper, @tagHelperPrefix, and @removeTagHelper directives are basically used to manage of Tag Helpers. The @namespace directive is basically used to specify the namespace that the ViewImports belongs to. With the help of @inject directive, it supports Dependency injection. We already use the @model directive in our previous applications when we are working with models. The @model directive is basically used to specify the Model for your view. The @using directive basically used to include the common namespaces globally so that you don’t have to include the namespaces in each and every view page.

Note: In this article, I am going to show you the use of the @using directive in ViewImports.cshtml file. Rest directives are going to be discussing in our upcoming articles.

Let us understand ViewImports with an example:
Create a model called Students within the Models folder of your application. Once you create the Students.cs class file then copy and paste the following code in it.
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}
As you can see, here we created the student model with five properties.

Modifying the Home Controller:
Modify the Home Controller as shown below.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            List<Student> listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
               new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
               new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };
            return View(listStudents);
        }
        public ViewResult Details(int Id)
        {
            var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" };
            return View(studentDetails);
        }
    }
}
As you can see, here we have two action methods. One action method is used to display all the student data while the other action method takes the student id as a parameter and return that student information.

Modifying the Index and Details view:
Index.cshtml:
@model List<FirstCoreMVCApplication.Models.Student>
@{
    Layout = null;
}
<html>
<head>
    <title>Index</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Branch</th>
                <th>Section</th>
                <th>Gender</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>
                        @student.StudentId
                    </td>
                    <td>
                        @student.Name
                    </td>
                    <td>
                        @student.Branch
                    </td>
                    <td>
                        @student.Section
                    </td>
                    <td>
                        @student.Gender
                    </td>
                </tr>
            }
        </tbody>
    </table>
   </body>
</html>
Details.cshtml:
@model FirstCoreMVCApplication.Models.Student
@{
    Layout = null;
}
<html>
<head>
    <title>Student Detaills</title>
</head>
<body>
    <div>
        StudentId : @Model.StudentId
    </div>
    <div>
        Name : @Model.Name
    </div>
    <div>
        Branch : @Model.Branch
    </div>
    <div>
        Section : @Model.Section
    </div>
    <div>
        Gender : @Model.Gender
    </div>
</body>
</html>
In the above Index and Details view, we are using the @model directive to specify the model for the view. If you notice, then you can see in both the views we have specified the fully qualified name for the model such as “FirstCoreMVCApplication.Models.Student”. Now let us see how to move the namespace to the ViewImports file so that we can only specify the model name.

Creating ViewImports.cshtml file in ASP.NET Core MVC Application:
In general, _ViewImports.cshtml files are created within the Views or within the subfolder of the Views folder. To create the “_ViewImports.cshtml” file right-click on the Views folder and then select the “Add – New Item” option from the context menu, which will open the “New Item” window. From the “New Item” window search for “Razor” and then select the “Razor View Import” and click on the “Add” button as shown in the below image which should create the “_ViewImport.cshtml” within the “Views” folder.
Creating ViewImports.cshtml file in ASP.NET Core MVC Application

Once the _ViewImports.cshtml file is created, then copy and paste the following code in it.
@using FirstCoreMVCApplication.Models;
As we placed the above namespace in the ViewImports file, now all the types that are present in the above namespace are available to each and every view in the “Home” folder. So now we don’t need to type the fully qualified name of the Type. So, modify the Index and Details view as shown below.
ViewImports in ASP.NET Core MVC

As you can see in the above image, we are removing the namespace and only specified the model name. Run the application and it should work as expected.

_ViewImports file is hierarchical Order in ASP.NET Core MVC:
Just like the _ViewStart file, the _ViewImports file is also hierarchical. It is also possible to pace the _ViewImports in the subfolder of the Views folder as shown in the below image. Here we have one _ViewImports file in the Views folder and another _ViewImports file within the Home folder.
_ViewImports.cshtml in ASP.NET Core MVC

The settings that are specified in the _ViewImports file present in the Home subfolder will overwrite the settings specified in the _ViewImports file in the Views folder.

Note: If you specified a setting in the view itself, then that setting overrides the matching settings specified in the parent _ViewImports files in the folder hierarchy.

In the next article, I am going to discuss How to Install and use Bootstrap in ASP.NET Core MVC Application. Here, in this article, I try to explain the ViewImports in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand the concept of ViewImports in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Monday, August 31, 2020

ViewStart in ASP.NET Core MVC

 Admin     August 31, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the ViewStart in ASP.NET Core MVC Application. Please read our previous article before proceeding to this article as it is a continuation part of our previous article. In our previous article, we discussed the Sections in the Layout Page in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. Why do we need _ViewStart.cshtml file in ASP.NET Core MVC Application?
  2. What is _ViewStart.cshtml file in ASP.NET Core MVC Application?
  3. How to create _ViewStart.cshtml file in ASP.NET Core MVC Application?
  4. How to set the Layout Property in ViewStart.cshtml file?
  5. Understanding the hierarchical of _ViewStart.cshtml file.
  6. How to select a layout conditionally in the ViewStart file?
Why do we need _ViewStart.cshtml file in ASP.NET Core MVC Application?
As of now, we have used the Layout Property to associate a view with a layout view as shown below.
Layout = “~/Views/Shared/_Layout.cshtml”;
Suppose, we have 100 views in our application and all the 100 views want to use the same layout file. Then we need to set the Layout Property as shown in the above image in all the 100 views. This violates the DRY (Don’t Repeat Yourself) Principle and has the following disadvantages.
  1. Redundant Code
  2. Maintenance Overhead
Suppose tomorrow you want to use a different Layout, then you need to update the Layout Property in each and every individual view. This process is tedious, time-consuming as well as error-prone because you may miss updating the Property in some of the views. To solve the above problems we need to use the _ViewStart.cshtml file.

What is _ViewStart.cshtml file in ASP.NET Core MVC Application?
In ASP.NET Core MVC Application, the _ViewStart.cshtml the file is a special file and the code present in this file is going to be executed before the code in an individual view is executed. So, you can set the Layout Property in this file as shown in the below image instead of setting the Layout Property in each individual view which is going to be executed before the actual view is executed.
_ViewStart.cshtml file in ASP.NET Core MVC Application

Once you set the Layout Property in _ViewStart.cshtml file as shown in the above image, then maintaining the application becomes much easier. So, in the future, if you want to change the layout file, then you just need to change the code in one place only i.e. in the _ViewStart.cshtml file.

How to create _ViewStart.cshtml file in ASP.NET Core MVC Application?
In general, the _ViewStart.cshtml files are created within the Views or within the subfolder of the Views folder. To create “_ViewStart.cshtml” file right click on the Views folder and then select the “Add – New Item” option from the context menu, this will opens the “New Item” window. From the “New Item” window search for “Razor” and then select the “Razor View Start” and click on the “Add” button as shown in the below image which should create the “_ViewStart.cshtml” within the “Views” folder.
How to create _ViewStart.cshtml file in ASP.NET Core MVC Application?

How to set the Layout Property in ViewStart.cshtml file?
Once the ViewStart.cshtml the file is created then modify the file as shown below to set the Layout property.
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Then we need to remove the Layout property on individual views. So, modify the Index view as shown below.
@{
    ViewBag.Title = "Home Page";
}
<h1>Home Page</h1>
@section Scripts {
    <script src="~/js/CustomJavascript.js"></script>
}
With the above changes in place, now run the application and it should display the output as expected.

Understanding the hierarchical of _ViewStart.cshtml file:
As we already discussed we can place the ViewStart file Views folder and its subfolder. So, we need to understand the hierarchical order of the ViewStart file. Let us understand this with an example.

Let us first create another layout file with the name _MyLayout.cshtml within the shared folder. Once you create the _MyLayout.cshtml file, then copy and paste the following code.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @if (IsSectionDefined("Scripts"))
    {
        @RenderSection("Scripts", false)
    }
</body>
</html>
With this Layout, now we have two layouts (_Layout.cshtml and _MyLayout.cshtml) for our application.

Creating ViewStart File within the Home Folder:
Let add another ViewStart file within the Home Folder which is present within the Views folder. Once you create the ViewStart file then modify the file as shown below. Here, we are setting the newly created _MyLayout.cshtml in the Layout property.
@{
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}
With the above changes, the Views folder of your application should looks as shown below.
Creating ViewStart File within the Home Folder

As you can see in the above image, we have placed one ViewStart file in the Views folder and another ViewStart file in the Home sub-folder. Now run the application and see the output.
ViewStart.cshtml file in ASP.NET Core MVC Application

The above Index view uses MyLayout.cshtml view which we specified within the ViewStart File which is present inside the Home Folder. So, here the layout page which is specified in the ViewStart file in the Home sub-folder overwrites the layout page specified in the ViewStart file in the Views folder.

This means, all the views which are present within the Views folder will use the layout page which is specified in the ViewStart file in the Views folder, but the views which are present in the Home folder will use the layout page which is specified in the ViewStart file in the Home folder.

Note: If you don’t want to use the layout file which is specified in the ViewStart file, rather you want to use a different layout file then you need to use the Layout property in individual view to set the layout. If you don’t want to use any layout or if you want to render a view without layout then need to set the Layout property to null.

How to select a layout conditionally in the ViewStart file?
In an ASP.NET Core MVC application, you may have multiple layout views. Let’s say you have two Layouts such as _NonAdminLayout and _AdminLayout. If you want to select the Layout based on the user role i.e. if the user role is Admin then use _AdminLayout else use the _NonAdminLayout. Then you need to write the following logic within the _ViewStart.cshtml file which will select the layout based on the role of the logged-in user.
@{
    if (User.IsInRole("Admin"))
    {
        Layout = "_AdminLayout";
    }
    else
    {
        Layout = "_NonAdminLayout";
    }
}
In the next article, I am going to discuss the _ViewImports.cshtml in ASP.NET Core MVC Application. Here, in this article, I try to explain the ViewStart in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand the concept of ViewStart in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sections in Layout Page in ASP.NET Core MVC

 Admin     August 31, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Sections in the Layout Page in ASP.NET Core MVC Application. Please read our previous article where we discussed the Layout View in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. What are Sections?
  2. What is the need for Sections in Layout View in ASP.NET Core MVC Application?
  3. Understanding the RenderSection Method.
  4. How to use the RenderSection Method in ASP.NET Core MVC?
  5. How to Provide section Content in a View?
  6. Understanding How to make the layout section optional in ASP.NET Core MVC?
Sections in Layout View in ASP.NET Core MVC Application:
In ASP.NET Core MVC, the layout view contains one or more sections in it. The Sections in a layout view are used to organize where certain page elements should be placed. The sections in a layout view can be optional or mandatory.

Understanding the need for Sections with an Example:
In order to understand this, let us first create a custom javascript file. First, create a folder at the root level of the application with the name “wwwroot”. In general all the static files we need to be placed within this folder. Once you created the “wwwroot” folder create a subfolder within this with the name “js” and then add a javascript file with the name “CustomJavascript.js” within the js folder as shown in the below image.
Sections in Layout View in ASP.NET Core MVC

Situation1:
If we have a custom javascript file (i.e. CustomJavascript.js) and that file is being required by all the views of our application, then we need to place it in the Layout View of our application as shown below.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">
        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>
    </table>
    <script src="~/js/CustomJavascript.js">
</body>
</html>
Note: It is always a good programming practice to put all the script files before the closing body tag.

Situation2:
If you have a custom javascript file (i.e. CustomJavascript.js) and you want that file in some specific views. Let assume you want that file in the Index view but not in the Details view of Home Controller. In such scenarios, you can make use of the section.

Understanding the RenderSection Method:
Let us have a look at the signature of the RenderSection() method which is shown below.
Understanding the RenderSection Method in ASP.NET Core MVC

As you can see there are two overloaded versions of the RenderSection Method. The same is the case for the RenderSectionAsync method. The first version of the Render section method takes a single parameter (i.e. name) which specifies the name of the section. The second overloaded version takes two parameters. The first parameter (name) specifies the name of the section while the second parameter (required) specifies whether the section is required or optional.

How to use the RenderSection Method in ASP.NET Core MVC?
In your layout view, you need to call the RenderSection() method at the location where you want the section content to be rendered. In our example, we want the script file to be included just before the closing </body> tag. So, we are calling the @RenderSection() method just before the closing </body> tag as shown below.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">
        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>
    </table>
    @RenderSection("Scripts")
</body>
</html>
In the above code, we are using the first overloaded version of the RenderSection method which takes only the name parameter.

How to Provide section Content in a View?
In our layout view, we have created a section. Now let us understand how to provide section content in a view. Each and every view which wants to provide section content must include a section within the same. Here, you need to use the @section directive to include the section and provide the content.

In our example, we want to provide the section content from the Index view. So, modify the index view as shown below.
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Home Page</h1>
@section Scripts {
    <script src="~/js/CustomJavascript.js"></script>
}
Modify the Startup class as shown below.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace FirstCoreMVCApplication
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvcWithDefaultRoute();
        }
    }
}
Now run the application and navigate to Home/Index URL and you will see the out as expected. But, when you navigate to Home/Details URL, you will get the following error page.
Exception in Render Section

The reason for getting the above exception is the section is mandatory and we have not specified the section content in the Details view.

How to make the layout section optional in ASP.NET Core MVC?
We can make a layout section optional in ASP.NET Core MVC in two ways. They are as follows:

Way1: Use the RenderSection method which takes two parameters. Set the second parameter (i.e. the required) to false.
@RenderSection(“Scripts”, required: false)
Way2: Using the IsSectionDefined() method. This method returns a value that indicates whether the specified section is defined in the content page.
@if (IsSectionDefined(“Scripts”))
{
       @RenderSection(“Scripts”, required: false)
}
So, modify the _Layout.cshtml file as shown below to make the section as optional.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">
        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>
    </table>
    @RenderSection("Scripts", false)
</body>
</html>
With the above changes in place, run the application and navigate to both the URL and you should get the output as expected.

In the next article, I am going to discuss the _ViewStart.cshtml in ASP.NET Core MVC Application. Here, in this article, I try to explain the Sections in the Layout Page in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand the concept of Sections in Layout Page in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Layout View in ASP.NET Core MVC

 Admin     August 31, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Layout View in ASP.NET Core MVC Application. Please read our previous article where we discussed the Attribute Routing in ASP.NET Core MVC Application with examples. As part of this article, we are going to discuss the following pointers.
  1. Why do we need Layout View in ASP.NET Core MVC?
  2. What is a Layout?
  3. How to Create a Layout View in ASP.NET Core MVC Application?
  4. How to use a Layout View in ASP.NET Core MVC Application?
What is Layout?
The layouts are like the master pages in Webforms applications. The common UI code, which can be used in many views can go into a common view called layout.

Why do we need Layout View in ASP.NET Core MVC?
Nowadays, almost all web applications have the following sections.
  1. Website Header
  2. Website Footer
  3. Navigation Menus
  4. Main Content Area
Please have a look at the following image which shows the above mentioned four areas on a website.
Layout View in ASP.NET Core MVC

If you don’t have a layout view for your website, then you need to repeat the required HTML for the above-mentioned sections in each and every view of your application. This is violating the DRY (Don’t Repeat Yourself) principle as we are repeating the same code in multiple views. As a result, it is very difficult to maintain the application. For example, if you have to remove or add a menu item from the list of navigation menus or even if you want to change the header or footer of your website then you need to do this in each and every view which is tedious, time-consuming as well as error-prone.

Instead of putting all the sections (i.e. the HTML) in each and every view page, it is always better and advisable to put them in a layout view and then inherit that layout view in each and every view where you want that look and feel. With the help of layout views, now it is easier to maintain the consistent look and feel of your application. This is because if you at all need to do any changes then you need to do it only in one place i.e. in the layout view and the changes will be reflected immediately across all the views which are inherited from the layout view.

Layout View in ASP.NET Core MVC Application:
  1. Like the regular view in ASP.NET Core MVC, the layout view is also a file with a .cshtml extension
  2. If you are coming from ASP.NET Web Forms background, you can think of the layout view as the master page in asp.net web forms application.
  3. As the layout views are not specific to any controller, so, we usually place the layout views in a subfolder called “Shared” within the “Views” folder.
  4. By default, in ASP.NET Core MVC Application, the layout view file is named _Layout.cshtml.
  5. The leading underscore in the file name indicates that these files are not intended to be served directly by the browser.
  6. In ASP.NET Core MVC, it is also possible to create multiple layout files for a single application. For example, you may have one layout file for the admin users and another layout file for non-admin users of your application.
How to Create a Layout View in ASP.NET Core MVC Application?
In order to create a layout view in ASP.NET Core MVC, you need to follow the below steps.
  1. Right-click on the “Views” folder and then add a new folder with the name “Shared“.
  2. Next, Right-click on the “Shared” folder and then select the “Add” – “New Item” option from the context menu which will open the Add New Item window.
  3. From the “Add New Item” window search for Layout and then select “Razor Layout”, give a meaning full name (_Layout.cshtml) to your layout view and finally click on the “Add” button as shown below which should add _Layout.cshtml file within the Shared folder.

How to Create a Layout View in ASP.NET Core MVC Application

Note: In this article, I am going to show you how to create and use a layout file and in our upcoming articles, I will show you how to use website header, footer, and navigation menus.

Understanding the _Layout.cshtml file:
Let us have a look at the auto-generated HTML code in the _Layout.cshtml file. The following HTML is auto-generated in the _Layout.cshtml file.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>
As you can see in the above layout file, it contains the standard Html, head, title, and body elements. As the above elements are present in the layout file, so you don’t have to repeat all the above elements in each and every view.

The View or Page-specific title is retrieved by using the @ViewBag.Title expression. For example, when the “index.cshtml” view is rendered using this layout view, then the index.cshtml view will set the Title property on the ViewBag. This is then retrieved by the Layout view using the expression @ViewBag.Title and set as the value for the <title> tag.

The @RenderBody() specifies the location where the view or page-specific content is injected. For example, if “index.cshtml” view is rendered using this layout view, then index.cshtml view content is injected at the location.

Let us modify the _Layout.cshtml page as shown below to include the header, footer, left navigation menus, and main content area section.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="font-family: Arial; width: 800px;">
      <tr>  
            <td colspan="2" style="text-align: center;">
                <h3>Website Header</h3>
            </td>
      </tr>
      <tr>
            <td style="width: 200px;">
                <h3>Left Navigation Menus
            </td>
            <td style="width: 600px;">
                @RenderBody()
            </td>
      </tr>
      <tr>
            <td colspan="2" style="font-size: x-small; text-align: center;">
                <h3>Website Footer</h3>
            </td>
      </tr>
</table>
</body>
Modifying the Startup class:
Please modify the Startup class as shown below where we configure the required services for MVC.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace FirstCoreMVCApplication
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}
Modifying the Home Controller:
Please modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
        
        public ViewResult Details()
        {
            return View();
        }
    }
}
As you can see here we have created two action methods i.e. Index and View.

Using Layout view in ASP.NET Core MVC Application:
Now we are going to create the Index and Details views using the Layout view. In order to render a view using the layout view (_Layout.cshtml), you need to set the Layout property.

Index.cshtml:
Please modify the Index view as shown below to use the layout view.
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Home Page

Details.cshtml:
Please modify the Details view as shown below to use the layout view.
@{
    ViewBag.Title = "Details Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Details Page

Now run the application and navigate to the Home/Index URL which should display the page as shown below.
---------------------how to create and use layout files in ASP.NET Core MVC
That’s it for today. In the next article, I am going to discuss Sections in the layout page in ASP.NET Core MVC Application. Here, in this article, I try to explain the need and how to create and use layout files in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand the concept of Layout View in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

ASP.NET Core Attribute Routing using Tokens

 Admin     August 31, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the ASP.NET Core Attribute Routing using Tokens with examples. Please read our previous article before proceeding to this article as we are going to work with the same example that we worked in our previous article. In our previous article, we discussed Attribute Routing in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. Understanding Tokens in Attribute Routing.
  2. Token Example in Attribute Routing.
  3. Advantages of using Tokens in Attribute Routing.
  4. Do we need to write the action token on each action method?
  5. Attribute Routing vs Conventional Routing in ASP.NET Core.
Tokens in Attribute Routing:
In ASP.NET Core, the Route Attribute support token replacement. It means we can enclose the token (i.e. controller and action) within a pair of square-braces ([ ]). The tokens (i.e. [controller] and [action]) are then replaced with the values of controller and action method name where the route is defined.

Token Example in Attribute Routing:
Let us understand this with an example. Please modify the Home Controller class as shown below. Here we are applying the token [controller] on the Home Controller and at the same time, we are applying the token [action] on all the action methods.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    [Route("[controller]")]
    public class HomeController : Controller
    {
        [Route("[action]")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        [Route("[action]")]
        public string Details()
        {
            return "Details() Action Method of HomeController";
        }
    }
}
With the above controller and action tokens in place, now you can access the Index action method of Home Controller with the URL /Home/Index. Similarly, you can access the Details action method using the URL /Home/Details. Now run the application and see everything is working as expected.

Advantages of Tokens in Attribute Routing:
The main advantage is that in the future if you rename the controller name or the action method name then you do not have to change the route templates. The application is going to works with the new controller and action method names.

How to make the Index action method as the default action?
With the controller and action tokens in place, if you want to make the Index action method of Home Controller as the default action, then you need to include the Route(“”) attribute with an empty string on the Index action method as shown below.
ASP.NET Core Attribute Routing using Tokens

Do we need to write the action token on each action method?
Not Really. If you want all your action methods to apply action token, then instead of including the [action] token on each and every action method, you can apply it only once on the controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        
        public string Details()
        {
            return "Details() Action Method of HomeController";
        }
    }
}
Attribute Routing vs Conventional Routing in ASP.NET Core:
In Attribute Routing, we need to define the routes using the Route attribute within the controller and action methods. The Attribute routing offers a bit more flexibility than conventional based routing. However, in general, the conventional based routings are useful for controllers that serve HTML pages. On the other hand, the attribute routings are useful for controllers that serve RESTful APIs.

However, there is nothing stopping you from mixing conventional based routing with attribute routing in a single application.

In the next article, I am going to discuss Layout View in ASP.NET Core MVC Application with one example. Here, in this article, I try to explain the need and use of ASP.NET Core Attribute Routing using Tokens. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of ASP.NET Core Attribute Routing using Tokens
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Anonymous Types in C#
    Hi friends! Today we are going to learn about Anonymous Types in C#. Let's start with the Introduction Anonymous is a type that does...
  • Development Approach with Entity Framework
    In this article, I will discuss Development Approach with Entity Framework . The entity framework provides three different approaches when ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape