Populating Dropdown Menu Using AJAX In ASP.NET Core

Introduction

In this blog, we will study how to populate the dropdown menu using ajax call in asp.net net core step by step.

Step 1 - Add the jQuery CDN to your application

First of all, you need to add the jQuery CDN to your application that helps us to run the jQuery Code smoothly in the application.

Step 2 - Write the Ajax Call

The second step is to write the ajax call that is used to handle the asp.net Controller for bringing the data from the database in the form of JSON Object.

Add this Ajax call where you want to get the data from the database using the Asp.net Core Controller.

<script type = "text/javascript" > $(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "/Bookings/FromLocation",
        data: "{}",
        success: function(data) {
            var s = '<option value="-1">Pickup Location</option>';
            for (var i = 0; i < data.length; i++) {
                console.log(data[i])
                s += '<option value="' + data[i].id + '">' + data[i].name + " " + data[i].address + '</option>';
            }
            $("#PickUpLocation").html(s);
        }
    });
}); 
</script> 

Step 3 - Write the Asp.net Core Controller

The third step is to write the controller that is used to handle the HTTP request and bring the data from the database.

Note: the name of the controller should be the same as in the ajax call.

public Object FromLocation()
{
    return (_context.Locations.Select(x => new
    {
        Id = x.Id,
        Name = x.Name,
        Address = x.Address
    }).ToList().Where(x => x.Name != null && x.Address != null));
}

Step 4 - Pass the Data to Dropdown Menu

One thing that should be in your mind  is that the id of the select option should be the same as in the Ajax call.

<div class="form-group">
    <label asp-for="PickUpLocation" class="control-label"></label>
        <div class="form-group">
            <select class="form-control" asp-for="PickUpLocation" id="PickUpLocation" name="PickUpLocation"></select>
            <span asp-validation-for="PickUpLocation" class="text-danger"></span>
        </div>
</div>

Output

Now you can see that our data is now populated in the dropdown menu

Populating the Dropdown Menu using Ajax in Asp .NET Core