Cascading drop-down lists in C# MVC using jquery

I'm working on Cascading dropdown lists in C# MVC using jquery, I'm populating the drop=downs from Database. But the drop-down doesn't populate according to the selection in the previous drop. Could you please tell what is it that I'm doing wrong? I think the public JsonResult GetLengthList(int MaterialId) is not being hit at all.

Length is a drop-down dependent on Material drop-down

below is my code.

Controller

[HttpGet]
public JsonResult GetLengthList(int MaterialId)
{
    db.Configuration.ProxyCreationEnabled = false;
    List<Length> LengthList = db.Lengths.Where(x => x.MaterialId == MaterialId).ToList<Length>();
    //List<Length> LengthList = db.Lengths.ToList();
    return Json(LengthList, JsonRequestBehavior.AllowGet);
}

View

<div class="form-group">
            @Html.LabelFor(model => model.Material.MaterialId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">

                @if (ViewBag.MaterialList != null)
                {

                    @Html.DropDownListFor(model => model.Material.MaterialId,
                     ViewBag.MaterialList as SelectList,
                     "Select", new { @class = "form-control" })
                }
                @Html.ValidationMessageFor(model => model.Material.MaterialId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Length.LengthId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">
                @Html.DropDownListFor(model => model.Length.LengthId,
                        new SelectList(" "),
                        "Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Length.LengthId, "", new { @class = "text-danger" })
            </div>
        </div>

Javascript in View

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script>
    $(document).ready(function () {
        $("#MaterialId").change(function () {
            $.get('@Url.Action("GetLengthList", "Drawing")', { MaterialId: $("#MaterialId").val() }, function (data) {
                $("#LengthId").empty();
                $.each(data, function (index, row) {
                    $("#LengthId").append("<option value='" + row.LengthId + "'>" + row.LengthValue + "</option>")
                });
            });
        })
    });
</script>

Answers 1

  • You do not have an <select> element with id="MaterialId". Your @Html.DropDownListFor(model => model.Material.MaterialId, ...) line of code generates a <select> with id="Material_MaterialId"

    Nor do you have an element with id="LengthId" - its id="Length_LengthId"

    Change you script to

    var lengthSelect = $('#Length_LengthId');
    $("#Material_MaterialId").change(function () {
        var id = $(this).val();
        $.get('@Url.Action("GetLengthList", "Drawing")', { MaterialId: id }, function (data) {
            lengthSelect.empty();
            $.each(data, function (index, row) {
                lengthSelect.append("<option value='" + row.LengthId + "'>" + row.LengthValue + "</option>")
            });
        });
    })
    

    I also suggest you study the code in this DotNetFiddle, in particular the controller code to know how to implement this correctly so that it can be used for editing existing items, and allow you to return the view if ModelState is invalid without losing the data the user entered, and to return only the data you need to generate the <option> elements.


Related Articles