In this article I will explain with an example, how to populate (bind) DropDownList using AngularJS AJAX and Entity Framework in ASP.Net Core MVC.
The DropDownList items (options) will be populated by fetching data from database using AngularJS AJAX and Entity Framework in ASP.Net Core MVC.
 
 
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 MVC: Populate (Bind) DropDownList using AngularJS and 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:
1. Use Newtonsoft JSON for serialization.
2. Add Anti-Forgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .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 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;
 
name space DropDownList_Angular_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 AJAX POST operation
This Action method handles the call made by the AngularJS 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: AngularJS, AJAX and JSON example in ASP.Net Core MVC.
 
Attributes
HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests.
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 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]
    [ValidateAntiForgeryToken]
    public JsonResult AjaxMethod()
    {
        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 View 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 View using the AntiForgeryToken function of the HTML Helper class.
Note: For more details please refer my article, ASP.Net Core MVC: Using AntiForgery Token with jQuery AJAX.
 
The HTML DIV consists of an HTML DropDownList element (SELECT).
The $http service is used to make an AJAX call to the Controller’s Action 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 Controller’s Action method.
3. dataType – The format of the data i.e. XML or JSON.
4. data – The parameters to be sent to the Controller's Action 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.
 
@{
    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: "/Home/AjaxMethod",
                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="customerinCustomers" value="{{customer.Value}}">
                {{customer.Text}}
            </option>
        </select>
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: Populate (Bind) DropDownList using AngularJS and AJAX
 
 
Downloads