2
Answers

How to fill dropdown using JQUERY on partial View dropdown html

Photo of Asht T

Asht T

Jun 17
392
1

       PArtial view html select dropdown not  filling using jquey, how to fill  using jquery ?

Answers (2)

5
Photo of Jignesh Kumar
29 39.5k 2.9m Jun 17

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

4
Photo of Vishal Yelve
105 17.2k 634.2k Jun 17

Hi Asht, 

 --- Controller 

[HttpGet]
    public ActionResult GetCities(int stateId)
    {
        var cities = db.Cities.ToList();
        List<SelectListItem> cityList = new List<SelectListItem>();
        foreach (City city in cities)
        {
            cityList.Add(new SelectListItem
            {
                Text = city.CityName,
                Value = city.CityId.ToString()

            });
        }
        ViewBag.City = cityList;
        return View("_City");
    }
partial View


<div class="form-group col-md-6">
    @Html.LabelFor(model => model.CityName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.CityName, (IEnumerable<SelectListItem>)ViewBag.City, "Select City", new { @class = "form-control col-md-3", @id = "ddlCities" })
    </div>
</div>

 

 --- View  page 
<div id="partialCityView"></div>


<script type="text/javascript">
        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);
                }
            });
        }
    </script>