In this article I will explain with an example, how to populate (bind) DropDownList using jQuery AJAX and Entity Framework in ASP.Net Core Razor Pages.
The DropDownList items (options) will be populated by fetching data from database using jQuery AJAX and Entity Framework in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: 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 the Anti-Forgery Token and JSON Serializer setting
The first step is to configure the Anti-Forgery Token and JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core Razor Pages: Populate (Bind) DropDownList using jQuery AJAX
 
2. Add the following namespaces.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to:
1. Add MVC Services for Razor Pages.
2. Use Newtonsoft JSON for serialization.
3. Add Anti-Forgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
 
For more details, regarding how to configure Anti-Forgery Token and JSON Serializer setting in ASP.Net Core Razor Pages, please refer my article Sending AntiForgeryToken with AJAX requests in ASP.Net Core Razor Pages.
 
 
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 Razor Pages and Entity Framework, please refer my ASP.Net Core Razor Pages: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core Razor Pages.
 
using Microsoft.EntityFrameworkCore;
 
name space DropDownList_AJAX_Razor_Core
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<Customer> Customers { get; set; }
    }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of following two Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
 
Handler method for handling jQuery AJAX operation
This Handler method handles the call made by the jQuery AJAX function in the Razor Page.
Note: The following Handler method handles AJAX calls and hence the return type is set to JsonResult. For more details, please refer my article Using jQuery AJAX in ASP.Net Core Razor Pages.
 
Attributes
ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
 
Inside this Handler 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 IndexModel : PageModel
{
    private DBCtx Context { get; }
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public void OnGet()
    {
    }
 
    [ValidateAntiForgeryToken]
    public JsonResult OnPostGetCustomers()
    {
        List<SelectListItem> customers = (from customer in this.Context.Customers.Take(10)
                                         select new SelectListItem
                                         {
                                             Value = customer.CustomerID,
                                             Text = customer.ContactName
                                         }).ToList();
        return new JsonResult(customers);
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML DropDownList element (SELECT).
The Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
Note: For more details please refer my article, Sending AntiForgeryToken with AJAX requests in ASP.Net Core Razor Pages.
 
Inside the jQuery document ready event handler, an AJAX call is made to the Handler method using the jQuery AJAX function.
The URL for the jQuery AJAX call is set to the handler method of the Razor PageModel i.e. /Index?handler=GetCustomers.
Note: In the Razor PageModel, the Handler method name is OnPostGetCustomers but here it will be specified as GetCustomers when calling from the Razor HTML Page.
 
The value of the Anti-Forgery Token is read from the Hidden Field and passed as Request Header in the jQuery AJAX call.
Note: Without passing Anti-Forgery Token, the AJAX call to the Handler method of the Razor PageModel will not work.
 
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.
@page
@model DropDownList_AJAX_Razor_Core.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <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: "/Index?handler=GetCustomers",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                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 Razor Pages: Populate (Bind) DropDownList using jQuery AJAX
 
 
Downloads