Hello,
Please check step by step :
Create main view and include partial view inside main view:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="dropdownContainer">
@Html.Partial("_DropdownPartial", Model.DropdownItems)
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Create partial view with dropdown :
@model IEnumerable<SelectListItem>
<select id="myDropdown" class="form-control">
<option value="">Select an option</option>
@foreach (var item in Model)
{
<option value="@item.Value">@item.Text</option>
}
</select>
Write Jquery function to fetch data from your controller action method,
<script>
$(document).ready(function() {
function populateDropdown() {
$.ajax({
url: '@Url.Action("GetDropdownData", "Home")', // URL to fetch data
type: 'GET',
success: function(data) {
var dropdown = $('#myDropdown');
dropdown.empty(); // Clear existing options
dropdown.append('<option value="">Select an option</option>'); // Add default selection option
// Loop through the data and append options in your dropdonw
$.each(data, function(index, item) {
dropdown.append($('<option>', {
value: item.Value,
text: item.Text
}));
});
},
error: function(xhr, status, error) {
console.error('Failed to fetch data: ' + error);
}
});
}
// Call the function to populate the dropdown
populateDropdown();
});
</script>
Create a Database call to get data and send to jquery call:
public class HomeController : Controller
{
public ActionResult Index()
{
// Pass an empty list initially
var model = new YourViewModel
{
DropdownItems = new List<SelectListItem>()
};
return View(model);
}
[HttpGet]
public JsonResult GetDropdownData()
{
// Fetch your data from a database or any other source as per your requirement
// Here I have created sample data
var items = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Value 1" },
new SelectListItem { Value = "2", Text = "Value 2" },
new SelectListItem { Value = "3", Text = "Value 3" }
};
return Json(items, JsonRequestBehavior.AllowGet);
}
}
Please follow above step carefully your data will load into your dropdown