PArtial view html select dropdown not filling using jquey, how to fill using jquery ?
Loading
PArtial view html select dropdown not filling using jquey, how to fill using jquery ?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceNov 23–27, 2026Live onlineFree to attendVisit the site
Jignesh KumarRank #91 · 22.9K reputationPosted Jun 17, 2024, 9:12 AM EDT
Hello,
Please check step by step :
Create main view and include partial view inside main view:
Create partial view with dropdown :
Write Jquery function to fetch data from your controller action method,
$(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('Select an option'); // Add default selection option // Loop through the data and append options in your dropdonw $.each(data, function(index, item) { dropdown.append($('', { 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(); });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() }; 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 { 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
Vishal YelveRank #178 · 13.6K reputationPosted Jun 17, 2024, 9:08 AM EDT
Hi Asht,
--- Controller [HttpGet] public ActionResult GetCities(int stateId) { var cities = db.Cities.ToList(); List cityList = new List(); foreach (City city in cities) { cityList.Add(new SelectListItem { Text = city.CityName, Value = city.CityId.ToString() }); } ViewBag.City = cityList; return View("_City"); }--- View page function GetCity() { $.ajax({ url: '@Url.Action("GetCity", "Home")', dataType: "html", type: "GET", contentType: "application/json", success: function (response) { $('#partialCityView').html(response); }, error: function (err) { alert(err.responseText); } }); }