In this article I will explain with an example, how to populate (bind) DropDownList using jQuery AJAX and Entity Framework in ASP.Net Core MVC.
The DropDownList items (options) will be populated by fetching data from database using jQuery AJAX and Entity Framework in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core MVC, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Configuring JSON Serializer setting
The first step is to configure the JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core MVC: Populate (Bind) DropDownList using jQuery AJAX
 
2. Add the following namespace.
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to use Newtonsoft library for JSON serialization.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
 
For more details, regarding how to configure JSON Serializer setting in ASP.Net Core MVC, please refer my article ASP.Net Core: jQuery AJAX and JSON Example in ASP.Net Core MVC.
 
 
Model
The Model class consists of the following properties.
public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
}
 
 
Database Context
Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Note: For beginners in ASP.Net Core and Entity Framework, please refer my ASP.Net Core: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core.
 
using Microsoft.EntityFrameworkCore;
 
namespace DropDownList_AJAX_MVC_Core
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<Customer> Customers { get; set; }
    }
}
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling jQuery AJAX POST operation
This Action method handles the call made by the jQuery AJAX function in the View.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult. For more details, please refer my article ASP.Net Core: Return JSON from Controller in ASP.Net Core MVC.
 
Inside this Action method, the Top 10 records from the Customers table is fetched using Entity Framework and then a Generic List collection of SelectListItem class objects is generated.
Note: The Generic List collection of SelectListItem class objects is used since it allows to reduce the size of the object by only storing the CustomerID and the ContactName values for each Contact.
 
Finally, the populated Generic List collection of SelectListItem class objects is returned to the View in JSON format.
public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod(string name)
    {
        List<SelectListItem> customers = (from customer in this.Context.Customers.Take(10)
                                         select new SelectListItem
                                         {
                                             Value = customer.CustomerID,
                                             Text = customer.ContactName
                                         }).ToList();
        return Json(customers);
    }
}
 
 
View
The following View consists of an HTML DropDownList element (SELECT).
Inside the jQuery document ready event handler, a jQuery AJAX call is made to the Controller using the jQuery AJAX function.
The URL for the jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod.
Inside the Success event handler of the jQuery AJAX function, first the DropDownList is referenced and a default Item (Option) is added to it.
Then, a jQuery each loop is executed over the JSON array and one by one each item is added as an Option element to the DropDownList.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <select id="ddlCustomers"></select>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var ddlCustomers = $("#ddlCustomers");
            ddlCustomers.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{}',
                success: function (response) {
                    ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
                    $.each(response, function () {
                        ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: Populate (Bind) DropDownList using jQuery AJAX
 
 
 
Downloads