Implementing Cascading Dropdowns in ASP.NET MVC Using jQuery AJAX

Introduction

Cascading dropdowns are a common UI pattern where the selection in one dropdown dynamically updates the options available in another dropdown. This tutorial will guide you through setting up cascading dropdowns in an ASP.NET MVC application using jQuery and AJAX.

Code

@model YourNamespace.YourViewModel

@{
    ViewBag.Title = "Cascading Dropdown Example";
}

<!-- Dropdown for BrandId -->
<div class="form-group form-md-line-input form-md-floating-label">
    <label for="BrandId">Brand<span class="text-danger">*</span></label>
    @Html.DropDownListFor(m => m.BrandId, namespace.SelectedItems.GetBrandNameAll(), "Select Brand", new { @required = "required", @class = "form-control required", id = "BrandId" })
</div>

<!-- Dropdown for BrandlistId -->
<div class="col-md-3">
    <div class="form-group form-md-line-input form-md-floating-label">
        <label for="BrandlistId">Brand list<span class="text-danger">*</span></label>
        @Html.DropDownListFor(m => m.BrandlistId, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select Brand list", new { @class = "form-control required", id = "BrandlistId" })
    </div>
</div>

<script>
$("#BrandId").on("change", function () {
    var selectedBrandId = $(this).val();
    $("#BrandlistId").html(""); // Clear existing options
    getives(selectedBrandId); // Call function to populate BrandlistId dropdown
});

function getives(brandId) {
    $.ajax({
        url: '@Url.Action("method", "controller")', // Replace with your controller and action
        type: 'GET',
        dataType: 'json',
        data: { BrandId: brandId },
        success: function (data) {
            $("#BrandlistId").html(""); // Clear existing options
            var options = "<option value='0'>-Select Brandlist-</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    options += "<option value='" + data[i].Value + "'>" + data[i].Text + "</option>";
                }
            }
            $("#BrandlistId").html(options); // Populate BrandlistId dropdown with new options
        },
        error: function (xhr, status, error) {
            console.error("Error fetching brand lists: " + error);
        }
    });
}
</script>

@functions {
    public static List<SelectListItem> GetBrandNameAll() {
        ServiceAgentBranchModel _model = new ServiceAgentBranchModel();
        _model.BrandId = 0;
        _model.BrandlistId = 0;
        var d = MasterProvider.GetBrand(_model);
        var list = d.Select(r => new SelectListItem {
            Text = r.Brandval,
            Value = r.BrandId.ToString()
        }).ToList();
        return list;
    }
}

Explanation

  1. Setting Up Your ASP.NET MVC View: First, ensure you have a model with properties for BrandId and BrandlistId. Your view (YourView.cshtml) will include two dropdowns: one for BrandId and another for BrandlistId.
  2. Implementing JavaScript for AJAX Interaction: In your view, add JavaScript/jQuery code to handle the cascading behavior. This code will make an AJAX call whenever the BrandId dropdown changes, dynamically populating the BrandlistId dropdown based on the selected BrandId.
  3. Implementing Controller Action: In your controller, define an action (Method) that handles the AJAX request and returns JSON data based on the selected BrandId.
  4. Data Retrieval Logic: Ensure your GetBrandNameAll() and GetBrandListsForBrand() methods in the controller or service layer correctly fetch data for the initial BrandId dropdown and the cascading BrandlistId dropdown, respectively.

Conclusion

you can implement cascading dropdowns in your ASP.NET MVC application. This approach leverages jQuery and AJAX for dynamic interaction between dropdowns, enhancing the user experience by reducing unnecessary page reloads and providing responsive UI updates based on user selections. Adjust the data retrieval logic (GetBrandNameAll() and GetBrandListsForBrand()) according to your application's specific requirements and database structure.