In this article I will explain with an example, how to populate (bind) DropDownList using AngularJS AJAX and Entity Framework in ASP.Net Core Razor Pages.
The DropDownList items (options) will be populated by fetching data from database using AngularJS 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 AngularJS and 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");
}
 
 
 
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_Angular_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 AngularJS AJAX operation
This Handler method handles the AJAX call made from the AngularJS $http service in the Razor Page.
Note: The following Handler method handles POST call and will return JSON object and hence the return type is set to JsonResult. For more details please refer 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 Razor page 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 DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
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.
 
The HTML DIV consists of an HTML DropDownList element (SELECT).
The $http service is used to make an AJAX call to the Handler method. The $http service has following properties and methods.
Properties
1. method – The method type of HTTP Request i.e. GET or POST.
2. url – URL of the Handlers method.
3. dataType – The format of the data i.e. XML or JSON.
4. data – The parameters to be sent to the Handler method.
5. headers – List of headers to be specified for the HTTP Request.
 
Event Handler
1. success – This event handler is triggered once the AJAX call is successfully executed.
2. error – This event handler is triggered when the AJAX call encounters an error.
The response from the AJAX call is received in JSON format inside the Success event handler of the $http service and is assigned to the Customers variable which is used to populate the DropDownList using the ng-repeat directive.
Note: For more details on using the ng-repeat directive, please refer my article Populate (Bind) HTML Select DropDownList with Options using ng-repeat.
 
@page
@model DropDownList_Angular_Razor_Core.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.DefaultLabel = "Loading.....";
            var antiForgeryToken = document.getElementsByName("__RequestVerificationToken")[0].value;
            var post = $http({
                method: "POST",
                url: "/Index?handler=GetCustomers",
                dataType: 'json',
                data: {},
                headers: {
                    "Content-Type": "application/json",
                    "XSRF-TOKEN": antiForgeryToken
                }
            });
 
            post.success(function (data, status) {
                $scope.DefaultLabel = "Please select";
                $scope.Customers = data;
            });
 
            post.error(function (data, status) {
                $window.alert(data.Message);
            });
        });
    </script>
    @Html.AntiForgeryToken()
    <div ng-app="MyApp" ng-controller="MyController">
        <select>
            <option value="0" label="{{DefaultLabel}}"></option>
            <option ng-repeat="customer in Customers" value="{{customer.Value}}">
                {{customer.Text}}
            </option>
        </select>
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Populate (Bind) DropDownList using AngularJS and AJAX
 
 
Downloads