MVC populate dropdownlist from database

June 15 2020 by Admin

In this article, we will explain how to Populate Dropdownlist from Database in ASP.NET Core with an example and sample code.


In this article, we will explain how to Populate Dropdownlist from Database in ASP.NET Core with an example and sample code. We have used the razor view engine and bound the Dropdownlist from the database using ADO.net. It's a very simple way of binding Dropdownlist. In this example, we have taken employee's and customer's data for binding a Dropdownlist. You can see the example code below. Visual Studio Code is a lightweight but powerful source code editor. It is a fully open-source and cross-platform framework available on Windows, Linux, and Mac.

Step -1

Open Visual Studio Code.

Step -2

Click on the file in the menu and select Open Folder. We are creating a folder for project(SampleCode) and select created folder name.

Step -3

Go to Terminal and Select New Terminal in the menu. In the terminal window, type dotnet new mvc .

Step -4

Build and Run the MVC Application. In the terminal window, type dotnet Build and dotnet run .

Required Namespaces

We will need to use the following namespaces.

usingMicrosoft.AspNetCore.Mvc;

usingSampleCode.Models;

usingMicrosoft.Extensions.Configuration;

usingSystem.IO;

usingSystem.Data.SqlClient;

Views

We have provided razor view html below.

@modelSampleCode.Models.Dropdownlist

@{

ViewData["Title"]="HomePage";

}

</p> <p>Binding Dropdown List With Database in ASP.NET Core</p> <p>

CustomerName:

@Html.DropDownListFor(model=>model.custlist,newSelectList(Model.custlist,"custId","custName")

,new{@class="form-control"})



EmployeeName:

@Html.DropDownListFor(model=>model.emplist,newSelectList(Model.emplist,"Empid","EmpName")

,new{@class="form-control"})

Models

In this model we have two child class for dropdownlist binding. you can use your existing class for this activity.

publicclassDropdownlist

{

publicListemplist{get;set;}

publicListcustlist{get;set;}

}

publicclassEmployee_list

{

publicintEmpid{get;set;}

publicstringEmpName{get;set;}

}

publicclassCustomer_list

{

publicintcustId{get;set;}

publicstringcustName{get;set;}

}

HomeController

publicclassHomeController:Controller

{

publicIConfigurationRootGetConnection()

{

varbuilder=newConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appSettings.json").Build();

returnbuilder;

}

publicIActionResultIndex()

{Dropdownlistmulti_Dropdownlist=newDropdownlist

{

custlist=GetCustomerList(),

emplist=GetEmployeeList()

};

returnView(multi_Dropdownlist);

}

publicListGetCustomerList()

{

varconnection=GetConnection().GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;

SqlConnectioncon=newSqlConnection(connection);

SqlCommandcmd=newSqlCommand("SelectcustomerId,FirstNameasNameFromCustomers",con);

con.Open();

SqlDataReaderidr=cmd.ExecuteReader();

Listcustomers=newList();

if(idr.HasRows)

{

while(idr.Read())

{

customers.Add(newCustomer_list

{

custId=Convert.ToInt32(idr["customerId"]),

custName=Convert.ToString(idr["Name"]),

});

}

}

con.Close();

returncustomers;

}

publicListGetEmployeeList()

{

varconnection=GetConnection().GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;

SqlConnectioncon=newSqlConnection(connection);

SqlCommandcmd=newSqlCommand("Select*FromEmployees",con);

con.Open();

SqlDataReaderidr=cmd.ExecuteReader();

ListEmployees=newList();

if(idr.HasRows)

{

while(idr.Read())

{

Employees.Add(newEmployee_list

{

Empid=Convert.ToInt32(idr["EmpoyeeId"]),

EmpName=Convert.ToString(idr["EmpName"]),

});

}

}

con.Close();

returnEmployees;

}

}

Output

Download



Note: All contents are copyright of their authors.