Bind a dropdown on selection change of another dropdown using MVC and ajax

To bind a dropdown on selection change of another dropdown using MVC and Ajax, follow the steps below:

  • Step 1: Create a MVC Controller:
  • Create a controller in your MVC project to handle the AJAX request and return data for the second dropdown. In this example, let’s call it “DropdownController”.

    public class DropdownController : Controller
        {
            public ActionResult GetDropdownData(string selectedValue)
            {
                // Your logic to fetch data from the database or any other source based on the selected value of the first dropdown
    
                // Return data as JSON
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
        
  • Step 2: Set up the View:
  • In the view where your dropdowns are located, add the necessary HTML markup and JavaScript code to handle the AJAX request and populate the second dropdown.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
            // Attach a change event to the first dropdown
            $("#firstDropdown").change(function () {
                var selectedValue = $(this).val();
                
                // Send AJAX request to the controller to get data for the second dropdown
                $.ajax({
                    url: "/Dropdown/GetDropdownData",
                    type: "GET",
                    data: { selectedValue: selectedValue },
                    dataType: "json",
                    success: function (data) {
                        // Clear the second dropdown
                        $("#secondDropdown").empty();
                        
                        // Loop through the returned data and append options to the second dropdown
                        $.each(data, function (index, item) {
                            $("#secondDropdown").append($("<option>", {
                                value: item.value,
                                text: item.text
                            }));
                        });
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log("Error: " + errorThrown);
                    }
                });
            });
        });
    </script>
    
    <div>
        <label for="firstDropdown">First Dropdown:</label>
        <select id="firstDropdown">
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
    </div>
    
    <div>
        <label for="secondDropdown">Second Dropdown:</label>
        <select id="secondDropdown">
            <option value="">-- Select --</option>
        </select>
    </div>
        

Related Post

Leave a comment