Inserting Data into Cosmos DB Using ASP.NET Core API

In this article, we will learn how to insert the data into the Azure Cosmos DB with SQL API using the ASP.NET Core API. Let's learn step by step.

Step 1: Set up Prerequisites

To perfrom the insert  operation in the Azure Cosmos DB we are required the following one the of the Prerequisites.

  • Azure Subscription OR
  • Azure Cosmos DB Emulator 

Azure Subscription 

To create the Azure cloud Cosmos DB account, you need an active Azure subscription. When you create the Cosmos DB account on the cloud, the Azure Cosmos DB Serverless account provides the first 1000 RU and 25 GB of storage for free per subscription.

Refer to the following link to learn the basics and how to create the Azure Cosmos DB account.

Azure Cosmos DB Emulator (offline)

As explained, the first approach requires an active Azure subscription as well as an active internet connection, which is not feasible for everyone who just wants to explore or learn about the Azure Cosmos DB.

To overcome the preceding issue, we can use the Azure Cosmos DB capabilities and features using the Azure Cosmos DB Emulator without an active Azure subscription or an active internet connection.

The Azure Cosmos DB Emulator currently does not have support for all the NoSQL API's, but it will support the most commonly used NoSQL API's such as the SQL API and Mongo DB API, and in the future it may also support all the Cosmos DB API's.

The following is the link to download the Azure Cosmos DB Emulator.

After clicking on the link, the official Microsoft documentation website gets opened, from which you can find and install the latest version of the Azure Cosmos DB Emulator.

Step 2: Create Azure Cosmos DB 

In this article, we are going to use the Azure Cosmos DB emulator instead of a Cloud Azure Cosmos DB account. If you are a beginner, then please refer to the following articles to learn how to create an Azure Cosmos DB account.
We are using the Azure Cosmos DB emulator in this article. search for the Azure Cosmos DB emulator from the search bar of the window once you download and install the emulator, which looks like the following:



The preceding image shows the Azure CosmosDB Account of the emulator, which will provide the same features as the Cloud Azure CosmosDB Account for development. Now click on the explorer and create the database and container. The explorer will then look like this:



We are storing the employee basic data in the Azure CosmosDB, and we are planning to use Department as a partition key and ID as the unique id for our employee records.

Note:
  • The ID and Department properties should be part of your backend input while inserting or updating the records; otherwise, you will get the exceptions.
I hope you have completed the required setup as explained in this article, including the creation of the Azure Cosmos account and database.

Step 3: Create ASP.NET Core web api Project

  1. Start then  All Programs and select "Microsoft Visual Studio".
  2. Once the Visual Studio Opens, Then click on Continue Without Code.
  3. Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web Api Project Template.
  4. Then define the project name, location of the project, then click on the next button.
  5. On the next screen, provide the additional details: framework, authentication type, and check the Enable Open API Support checkbox as shown below.


The preceding steps will create the ASP.NET Core Web API application and solution explorer. It will look like what is shown in the following image.



Step 4: Add Microsoft.Azure.Cosmos Nuget Package Reference

The Microsoft.Azure.Cosmos is the the latest nuget package to interact with the Azure cosmos DB. The Microsoft.Azure.Cosmos supports the basic to custom and complex database operations, follow the following steps to add the Nuget package.

  1. Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  2. After as shown into the image and type in search box Microsoft.Azure.Cosmos
  3. Select Microsoft.Azure.Cosmos as shown into the image, 
  4. Choose version of Microsoft.Azure.Cosmos library and click on install button


I hope you have followed the same steps and installed the Microsoft.Azure.Cosmos nuget package.The next step is to delete the default controller and model class so we can start from scratch.


Step 5:Create the Model Class

  • First, delete the default model class, which is created outside the folder structure, so we can start from scratch. 
  • Next, create the folder named Model by right clicking on the solution explorer.
  • Create the model class Employee Model by right clicking on the Model folder, as shown in the following image


Now open the EmployeeModel.cs class file and add the following code.

EmployeeModel.cs

namespace EmployeeManagement.Model
{
    public class EmployeeModel
    {
        public string? id { get; set; }
        public string? Name { get; set; }
        public string? Country { get; set; }
        public string? City { get; set; }       
        public string? Department { get; set; }
        public string? Designation { get; set; }
        public DateTime? JoiningDate { get; set; }

    }
}

Step 6: Add the Controller

Create the Empty API Controller class EmployeeController by right clicking on the Controller folder as shown in the following image.



After adding the model class and API controller class, the solution explorer will look like the following:




Now open the EmployeeController.cs file and add the add the following configuration.
  • Define the following route at controller level, so that we can add the multiple Get, Post, Put, or Delete and avoid the name ambiguity exception.
    [ApiController]
    [Route("[api/[controller]/[action]]")]
    public class EmployeeController : ControllerBase
    {
    }

  • Declare the following variable and set the Azure Cosmos DB configuration by copying the details from step 2.
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";
}

Step 7: Create Method to Add Employee

Add the following code into the EmployeeController.cs class to Add the employees into the CosmosDB. This method takes input values using  the EmployeeModel class. 

        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        } 



As explained in step 2, we are passing the ID and Department as a partition key as part of the employee input payload while adding the employee details. These parameters must be part of the input parameter payload.

The entire code of the EmployeeController.cs class file will look like the following after adding all the methods together:

EmployeeController.cs

using EmployeeManagement.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;

namespace EmployeeManagement.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class EmployeeController : ControllerBase
    {
       
        // Cosmos DB details, In real use cases, these details should be configured in secure configuraion file.
        private readonly string CosmosDBAccountUri = "https://localhost:8081/";
        private readonly string CosmosDBAccountPrimaryKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        private readonly string CosmosDbName = "EmployeeManagementDB";
        private readonly string CosmosDbContainerName = "Employees";


        /// <summary>
        /// Commom Container Client, you can also pass the configuration paramter dynamically.
        /// </summary>
        /// <returns> Container Client </returns>
        private  Container  ContainerClient()
        {

            CosmosClient cosmosDbClient = new CosmosClient(CosmosDBAccountUri, CosmosDBAccountPrimaryKey);
            Container containerClient = cosmosDbClient.GetContainer(CosmosDbName, CosmosDbContainerName);
            return containerClient;
           
        }


        [HttpPost]
        public async Task<IActionResult> AddEmployee(EmployeeModel employee)
        {
            try
            {
                var container = ContainerClient();
                var response = await container.CreateItemAsync(employee, new PartitionKey(employee.Department));

                return Ok(response);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
               
        }

    }
}

Now, we have all the code and required configuration to work with Azure CosmosDB in our sample application.

Step 8: Run the ASP.NET Core API Application

Now press Keyboard F5 or the Visual Studio Run button to run the application. After running the application, the following screen will be shown in the browser with swagger UI having all the methods which we have created in our ASP.NET core web API, as shown in the following screenshot:




Now, we will test the functionality by using the Swagger UI, but you can use Postman or any other tool to execute the API endpoints.

Step 9: Azure Cosmos DB Data Insert Demo 

The following animated image shows how the data gets added to the Azure Cosmos DB with SQL API.

Add Employees


Summary

Swagger Failed to load API definition In ASP.NET Core API

In this article, we will learn how to resolve the ASP.NET Core API Swagger Failed to load API Definition issue.

You can refer to the following link for the related articles: 

What is the root cause of the API definition loading issue?

The default API controller route configuration is the cause of this issue. When we add the API controller in the ASP.NET Core API application, by default it has controller-specific routes, which means it can support only a single method for each of the HTTP verbs Post, PUT, Delete, GET, and Patch.

There may be a requirement when we need to create more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single API controller, and if you create the method with the default route configuration in the API controller class without modifying the default route configuration, then you will get the exception "Failed to load API definition" while loading the swagger UI in the ASP.NET Core web API.

What is the Solution?

The solution is that you have to change the default route configuration at the controller level when you have created more than one method with the HTTP verbs "post," "put," and "get." Delete or Put in the single API controller class.

Consider the following example: I have created the ASP.NET Core API application, which has by default one Get method, GetWeatherForecast, which returns the WeatherForecast. Then I have added one more Get method named WeatherForecastByCity in the default API Controller class without modifying the default route.

 [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet(Name = "WeatherForecastByCity")]
    public IEnumerable<WeatherForecast> Get(string city)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

When we have run the application, we will get the Swagger loading error,


Now change the default route at controller level which can support more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single controller.

[Route("api/[controller]/[action])]

Also, remove the name of the method from the HTTP verb, which is defined using the Name attribute; just define the HTTP verb and proper method name.


Change from

   [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }


To 
 
   [HttpGet]
    public IEnumerable<WeatherForecast> GetWeatherForecast()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

Full Code







d[ApiController] [Route("api/[controller]/[action]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> GetWeatherForecast() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] public IEnumerable<WeatherForecast> WeatherForecastByCity(string city) { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }

Now, run the application again after changing the default route, and you will see swagger loads without any issue.


Summary

I hope this article helps you fix the issue. "Swagger failed to load API definitions in the ASP.NET Core API." If you have any questions, then send them using the comment box.

Related Articles

DropDownList in ASP.NET Core

In this article, we will learn how to create and bind Dropdown List using ViewBag in ASP.NET Core MVC. Let's learn step by step by creating an ASP.NET Core application.

Step 1: Create ASP.NET Core MVC Application

  • Start then  All Programs and select "Microsoft Visual Studio".
  • Once the Visual Studio Opens, Then click on Continue Without Code.
  • Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web App (Model-View-Controller) Project Template.
  • Then define the project name, location of the project, Target Framework, then click on the create button.
The preceding steps will create the ASP.NET Core MVC application. If you are new to the ASP.NET core and know how to create an ASP.NET Core application in depth, then refer to my following article.

Step 2: Add controller class

Delete the existing controller for ease of understanding, then add a new controller by right clicking on the Controller folder in the created ASP.NET Core MVC application, give the Controller name Home or as you wish as in the following.


Now open the HomeController.cs file and write the following code into the Home controller class as in the following.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace BindDropDownList.Controllers
{
    public class HomeController : Controller
    {
      
        public IActionResult Index()
        {
            //Creating the List of SelectListItem, this list you can bind from the database.
            List<SelectListItem> cities = new()
            {
                new SelectListItem { Value = "1", Text = "Latur" },
                new SelectListItem { Value = "2", Text = "Solapur" },
                new SelectListItem { Value = "3", Text = "Nanded" },
                new SelectListItem { Value = "4", Text = "Nashik" },
                new SelectListItem { Value = "5", Text = "Nagpur" },
                new SelectListItem { Value = "6", Text = "Kolhapur" },
                new SelectListItem { Value = "7", Text = "Pune" },
                new SelectListItem { Value = "8", Text = "Mumbai" },
                new SelectListItem { Value = "9", Text = "Delhi" },
                new SelectListItem { Value = "10", Text = "Noida" }
            };

            //assigning SelectListItem to view Bag
            ViewBag.cities = cities;
            return View();
        }

       
    }
}

Step 3: Add View

Add an empty view named Index.cshtml and write the following code.

@{
    ViewData["Title"] = "Home Page";
}
<hr />
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <label  class="control-label"> Select City</label>

                <select name="products" class="form-control" asp-items="@ViewBag.cities"></select>


            </div>
        </div>
    </div>

Step 4: Run the Application.

Now press Keyboard F5 or Visual Studio run button to run the application. After running the application, the output will be shown on the browser, as in the following screenshot.


I hope, from all the above examples, you have learned how to bind the DropDownList using ViewBag in ASP.NET Core MVC.

Summary

I hope this article is useful for all readers. If you have a suggestion then please contact me.

Related Articles

Generating QR Code To Open Web URL In ASP.NET Core MVC

In the previous article, we have learned how to create a simple QR code which has a sample text. Now in this article we will learn how to generate the QR code to open the web page after scanning the QR code. As shown in the following image.



Let's learn step by step by creating an ASP.NET Core application.

Step 1: Create ASP.NET Core MVC Application

  • Start then  All Programs and select "Microsoft Visual Studio 2019".
  • Once the Visual Studio Opens, Then click on Continue Without Code.
  • Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web App (Model-View-Controller) Project Template.
  • Then define the project name, location of the project, Target Framework, then click on the create button.
The preceding steps will create the ASP.NET Core MVC application and solution explorer. It will look like as shown in the following image.


Delete the existing auto-generated code including controller and views for ease of understanding. We will add step by step while building the application.

Step 1: Add QRCoder Nuget Package Reference

The QRCoder is the open source pure C# library to generate the codes. The QRCoder supports the basic to custom and complex OR code generation, follow the following steps to add the Nuget package.
  • Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  • After as shown into the image and type in search box "QRCoder"
  • Select QRCoder as shown into the image
  • Choose version of QRCoder library and click on install button

I hope you have followed the same steps and installed the QRCoder nuget package.

Step 2: Create the Model Class

Create the model class QRCodeModel by right clicking on the model folder to take the input text for QR code as shown in the following image.


Now open the QRCodeModel.cs class file and add the following code.

using System.ComponentModel.DataAnnotations;

namespace GeneratingQRCode.Models
{
    public class QRCodeModel
    {
        [Display(Name = "Enter QRCode Text")]
        public string QRCodeText { get; set; }

    }
}

Step 3: Add the Controller

Create the Controller class by right clicking on the Controller folder as shown in the following image.


Now open the HomeController.cs file and add the following code.

using GeneratingQRCode.Models;
using Microsoft.AspNetCore.Mvc;
using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Static.QRCoder.PayloadGenerator;
namespace GeneratingQRCode.Controllers { public class HomeController : Controller { [HttpGet] public IActionResult CreateQRCode() { return View(); } [HttpPost] public IActionResult CreateQRCode(QRCodeModel qRCode) {
            
            string WebUri = new Url(qRCode.QRCodeText);
            string UriPayload =WebUri.ToString();
QRCodeGenerator QrGenerator = new QRCodeGenerator(); QRCodeData QrCodeInfo = QrGenerator.CreateQrCode(UriPayload, QRCodeGenerator.ECCLevel.Q);
QRCode QrCode = new QRCode(QrCodeInfo); Bitmap QrBitmap = QrCode.GetGraphic(60); byte[] BitmapArray = QrBitmap.BitmapToByteArray(); string QrUri = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(BitmapArray)); ViewBag.QrCodeUri = QrUri; return View(); } } //Extension method to convert Bitmap to Byte Array public static class BitmapExtension { public static byte[] BitmapToByteArray(this Bitmap bitmap) { using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); return ms.ToArray(); } } } }

Step 4: Create The View

Create the view with the name CreateQRCode using the model class QRCodeModel by right clicking on the view folder or right clicking in the controller class file as shown in the following image.


After clicking the Add button, it generates the view with the name CreateQRCode. Now open the CreateQRCode.cshtml file and replace the default generated code as follows:

CreateQRCode.cshtml

@model GeneratingQRCode.Models.QRCodeModel

@{
    ViewData["Title"] = "www.compilemode.com";
}
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateQRCode">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="QRCodeText" class="control-label"></label>
                <input asp-for="QRCodeText" class="form-control" />
                <span asp-validation-for="QRCodeText" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Generate QR Code" class="btn btn-primary text-center" />
            </div>
            <div class="form-group">

                <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
            </div>
        </form>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

In the preceding code you see the image tag src Uri assigned with ViewBag, which we have set from the HomeController class.

Step 5: Configure the Routing

We have modified the auto-generated files, so we have to set the default routing so that when you run the application, then the default view can start in the browser. Now open the Startup.cs and set the default routing as per our controller and the created view as shown in the following image.


After adding all the required files and configuration, the Solution explorer of our created ASP.NET core application will look like as follows.


Step 6: Run the Application.

Now press Keyboard F5 or Visual Studio run button to run the application. After running the application, the following screen will be shown in the browser. Enter the QR code text and click on the Generate QR code button, then it will generate the following code as in the following screenshot.


Step 7: Read the QR Code

Open the your mobile phone QR code reader application and scan it, it will show the website link which we have entered during the QR code creation and Go To Website, it will open the website as shown in the following demo.




Summary

I hope, from all the above examples, you have learned to generate QR Code which open the given URL using ASP.NET Core MVC. If you like it, share it with your friends, subscribe to the blog and YouTube channel for more such articles.

Multiple Layout Pages In ASP.NET Core MVC

The layout page shares the common design across all pages. There are many methods which are listed below to change the layout page dynamically in ASP.NET Core MVC.
  • While Adding View Page, Assign Layout Page .
  • Using View Start Page
I hope you have understood about the layout page from the preceding brief summary. Now let's implement it practically.
  • Start then All Programs and select "Microsoft Visual Studio 2019".
  • Once the Visual Studio Opens, Then click on Continue Without Code.
  • Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web App (Model-View-Controller) Project Template.
  • Then define the project name, location of the project, Target Framework, then click on the create button.
The preceding steps will create the ASP.NET Core MVC application.

Step 2:  Add user and admin controller controller.

Right click on the Controller folder in the created ASP.NET Core MVC application and add the two controller classes with names UserController and AdminController as follows.


The preceding two controller classes are added into the project which are User and Admin and create the following action methods in respective controller class.

UserController.cs

public class UserController : Controller  
    {  
        public IActionResult Login()  
        {  
            //write logic here  
            return View();  
        }  
    } 
AdminController.cs

public class AdminController : Controller  
   {  
       [HttpPost]  
       public IActionResult AddRole()  
       {  
           //write logic here  
           return View();  
       }  
   } 
For preceding two controllers we will use two different layout pages.

Step 3: Add Views and Layout pages

We can decide which layout page to be used while adding the view. Let us follow the following steps to add the layout page with view. Click on the View folder of the created ASP.NET Core MVC application as,


As shown in the preceding image, specify the view name and check the use layout page option and click the adding button, then the following default layout page will be added into the solution explorer. Now let's add another layout page named admin as in the following. Click on solution explorer and add the layout page as follows:



Now click on add button, then two layout pages are added under shared folder which are AdminLayoutPage and Layout.

Step 4: Set layout pages to view

We have created view and layout pages. Now let us assign layout pages to the views. There are many ways to assign layout page to the view which are listed as in the following:
  • Using wizard
  • Using ViewStart page
  • Using view method
Using wizard

You can use wizard to set the layout page while adding the view, steps are as follows:
  • Right click on view folder and select view template as,

Specify the view name and check on Use a layout page and click on browse button. The following window will appear,


Now choose layout page from preceding available Layout pages and click on ok button. The layout page will look like as follows,


Now click on add button then layout page reference added into the view page as,

So whenever you will add through wizard or manually the layout page reference need to be set in every view page where the layout page is needed.

Using ViewStart page

Adding reference of layout page in every page is very difficult and repetitive of code. Let us consider I have one controller which as twenty plus action method then each twenty views we need to add reference of layout page. Assume another requirement we need to set layout page according to condition basic or controller basic then we need to use Viewstart page.

Lets open the ViewStart.cshtm page and write the following code,

@{  
    string CurrentReq = Convert.ToString(Context.Request.HttpContext.Request.RouteValues["Controller"]);
dynamic Layout; switch (CurrentReq)
{ case "User": Layout = "~/Views/Shared/_Layout.cshtml"; break; default: //Admin layout Layout = "~/Views/Shared/_AdminLayoutPage.cshtml"; break; } }
Now run the application, the Login view will look like as follows in which we have used Layout page,

Now run AddRole view, Then the output will look like the following,

I hope from all the preceding examples, you have learned how to work with multiple layout pages in ASP.NET Core MVC.

Note:
  • Apply proper validation before using it in your project.
Summary

I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

Related Tutorials


How To Create an ASP.NET MVC Application

DropDownList in ASP.NET Core MVC

In this article, we will learn how to create and bind a dropdown list using ViewBag in ASP.NET Core MVC. Let's learn step-by-step by creating an ASP.NET Core application.

Step 1: Create ASP.NET Core MVC Application

  • Start then  All Programs and select "Microsoft Visual Studio 2019".
  • Once the Visual Studio Opens, Then click on Continue Without Code.
  • Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web App (Model-View-Controller) Project Template.
  • Then define the project name, location of the project, Target Framework, then click on the create button.
The preceding steps will create the ASP.NET Core MVC application. If you are new to the ASP.NET core and do not know how to create an ASP.NET Core application in depth, then refer to my following article.

Step 2: Add controller class

Delete the existing controller for ease of understanding, then add a new controller by right clicking on the Controller folder in the created ASP.NET Core MVC application, give the Controller name Home or as you wish as in the following.


Now open the HomeController.cs file and write the following code into the Home controller class as in the following.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace BindDropDownList.Controllers
{
    public class HomeController : Controller
    {
      
        public IActionResult Index()
        {
            //Creating the List of SelectListItem, this list you can bind from the database.
            List<SelectListItem> cities = new()
            {
                new SelectListItem { Value = "1", Text = "Latur" },
                new SelectListItem { Value = "2", Text = "Solapur" },
                new SelectListItem { Value = "3", Text = "Nanded" },
                new SelectListItem { Value = "4", Text = "Nashik" },
                new SelectListItem { Value = "5", Text = "Nagpur" },
                new SelectListItem { Value = "6", Text = "Kolhapur" },
                new SelectListItem { Value = "7", Text = "Pune" },
                new SelectListItem { Value = "8", Text = "Mumbai" },
                new SelectListItem { Value = "9", Text = "Delhi" },
                new SelectListItem { Value = "10", Text = "Noida" }
            };

            //assigning SelectListItem to view Bag
            ViewBag.cities = cities;
            return View();
        }

       
    }
}

Step 3: Add View

Add an empty view named Index.cshtml and write the following code.

@{
    ViewData["Title"] = "Home Page";
}
<hr />
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <label  class="control-label"> Select City</label>

                <select name="products" class="form-control" asp-items="@ViewBag.cities"></select>


            </div>
        </div>
    </div>

Step 4: Run the Application.

Now press Keyboard F5 or Visual Studio run button to run the application. After running the application, the output will be shown on the browser, as in the following screenshot.


I hope, from all the above examples, you have learned how to bind the DropDownList using ViewBag in ASP.NET Core MVC.

Summary

I hope this article is useful for all readers. If you have a suggestion then please contact me.

Related Articles

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode