简体   繁体   中英

Cascading dropdownlists ASP.NET Core MVC

What I would like to be able to accomplish is:

Have the user select a Model first which would then display all Engines related to that Model. I have been trying to adapt code from related problems, but without success.

Here is the code from one of my attempts.

Any help would be appreciated.

CarsController.cs

public ActionResult GetEnginesByModelId(int ModelId)
    {
        EnginesRepository enginesRepository = new EnginesRepository();
        List<Engine> engines = enginesRepository.GetAll(cascadeInclude: true).SelectMany(e => e.EngineModels).Where(em => em.ModelId == ModelId).Select(em => em.ParentEngine).ToList();

        return Json(engines);
    }

Create.cshtml

<div class="row">
        <div class="col-md-2 ">
                Model:
                <select asp-items="@Model.Models" id="models">
                </select>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2 ">
                Engines:
                <select id="engines"></select>
        </div>
    </div>

jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var items = "<option value='0'>Select</option>";
        $("#models").html(items);
    });
    $("#models").change(function () {
        var modelId = $("#models").val();
        var url = "/Cars/GetEnginesByModelId";

        $.getJSON(url, { ModelId: modelId }, function (data) {
            var item = "";
            $("#engines").empty();
            $.each(data, function (i, engine) {
                item += '<option value="' + engine.value + '">' + engine.text + '</option>'
            });
            $("#engines").html(item);
        });
    });
</script>

UPDATE: I managed to hit the controller and get the list of items but it displays "undefined". To show the items I use item.ToString() method. Here is the js and c# I used. JS

<script type="text/javascript">
    $(document).ready(function () {
        $("#models").on("change", function () {
            $list = $("#engines");
            $.ajax({
                url: "/Cars/GetEnginesByModelId",
                type: "GET",
                data: { id: $("#models").val() }, //id of the state which is used to extract cities
                traditional: true,
                success: function (result) {
                    $list.empty();
                    $.each(result, function (i, item) {
                        $list.append('<option value="' + item["EngineId"] + '"> ' + item["ToString()"] + ' </option>');
                    });
                },
                error: function () {
                    alert("Something went wrong call the police");
                }
            });
        });
    });
</script>

Create.cshtml

<div class="row">
        <div class="col-md-2 ">
            <div class="customDiv">
                Model:
                <select id="models" name="ModelId">
                    @foreach (var carModel in Model.Models)
                    {
                        <option value="@carModel.Id">@carModel.Name @carModel.Price$</option>
                    }
                </select>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2 ">
            <div class="customDiv">
                Engines:
                <select id="engines" name="EngineId">
                    @foreach (var engine in Model.Engines)
                    {
                        <option value="@engine.Id">@engine.ToString()</option>
                    }
                </select>
            </div>
        </div>
    </div>

The JS that worked for me

$(document).ready(function () {

$("#models").change(function () {
    $.get("/Cars/GetEnginesByModelId", { id: $("#models").val() }, function (data) {
        $("#engines").empty();
        $.each(data, function (index, row) {
            $("#engines").append("<option value='" + row.id + "'>" + row.name + "</option>")
        });
    });
})

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM