Cascade Dropdown List in ASP.NET Core 6 using Razor Pages:
Assuming you have two related entities, such as Country and State, and you want to create a form that allows the user to select a country and then a state based on the selected country. Here's how you can achieve this using jQuery and AJAX.
First, create your Country and State models:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public List<State> States { get; set; }
}
public class State
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
Then, create your controller action that returns the states based on the selected country:
Note:_context
is your Entity Framework context.
public IActionResult GetStates(int countryId)
{
var states = _context.States.Where(s => s.CountryId == countryId).ToList();
return Json(states);
}
Next, create your view that contains the two dropdown lists:
@model MyProject.Models.Country
<form>
<div>
<label for="countryId">Country:</label>
<select id="countryId" name="countryId">
<option value="">-- Select a country --</option>
@foreach (var country in Model)
{
<option value="@country.Id">@country.Name</option>
}
</select>
</div>
<div>
<label for="stateId">State:</label>
<select id="stateId" name="stateId" disabled>
<option value="">-- Select a state --</option>
</select>
</div>
</form>
Use Razor syntax to iterate over a list of countries and populate the first dropdown list. We also disable the second dropdown list until a country is selected.
Finally, add some jQuery code to handle the change event of the first dropdown list and make an AJAX request to retrieve the states based on the selected country:
$(document).ready(function () {
$('#countryId').change(function () {
var countryId = $(this).val();
if (countryId) {
$.ajax({
type: "GET",
url: "/Home/GetStates",
data: { countryId: countryId },
success: function (data) {
var stateDropdown = $('#stateId');
stateDropdown.empty();
stateDropdown.append($('<option/>').val('').text('-- Select a state --'));
$.each(data, function (i, state) {
stateDropdown.append($('<option/>').val(state.id).text(state.name));
});
stateDropdown.prop('disabled', false);
}
});
} else {
$('#stateId').empty().prop('disabled', true);
}
});
});
In this example, we handle the change event of the first dropdown list using jQuery's change()
function. We then retrieve the selected country ID and make an AJAX request to the GetStates()
action in our controller, passing the selected country ID as a parameter.
When the AJAX request returns successfully, we populate the second dropdown list with the returned states and enable it. If no country is selected, we empty the second dropdown list and disable it.
That's it! With this code, you should now have a Cascade Dropdown List that allows users to select a country and then a state based on the selected country.