Make drop down list dependent on another drop down in MVC Core

Viewed 495

This is similar to the question asked Drop-down box dependent on the option selected in another drop-down box except I would like to use a C# class to keep a list of the drop down values rather than pure html. The jQuery used in the previous question does not work with what I am trying to do.

I want a user to select a vehicle Make and then have the model List be dependent on what Make was selected

C# Class: DropDowns.cs

public static List<SelectListItem> MakeList (string defaultLabel = "---"){

    List<SelectListItem> makeList = new List<SelectListItem>();

    makeList.Add(new SelectListItem {Text="defaultLabel", Value = ""});
    makeList.Add(new SelectListItem {Text="Ford", Value = "Ford"});
    makeList.Add(new SelectListItem {Text="Toyota", Value = "Toyota"});

    return makeList;}

public static List<SelectListItem> ModelList (string defaultLabel = "---"){

    List<SelectListItem> modelList = new List<SelectListItem>();

    modelList.Add(new SelectListItem {Text="defaultLabel", Value = ""});

    //Ford models
    modelList.Add(new SelectListItem {Text="F-150", Value = "F-150"});
    modelList.Add(new SelectListItem {Text="Mustang", Value = "Mustang"});

    //Toyota models
    modelList.Add(new SelectListItem {Text="Rav4", Value = "Rav4"});
    modelList.Add(new SelectListItem {Text="Tundra", Value = "Tundra"});

    return modelList;}

HTML: myView.cshtml

<select name="make" asp-for="Make" asp-items="DropDowns.MakeList()"></select>
<select name="model" asp-for="Model" asp-items="DropDowns.ModelList()"></select>

I'm not really sure if it is possible to use a jQuery for asp-items. Maybe I would need to add if statements in my modelList?

1 Answers

asp-items relies on the server to parse, if the drop-down list is dynamically changed in this way, the client and the server need to maintain real-time interaction. So this method is impossible. You need to use jQuery.

When you see the page, asp-items have been parsed into html. At this time, html can be changed through jQuery.

<select name="make" asp-for="Make" asp-items="DropDowns.MakeList()"></select>
<select name="model" asp-for="Model" asp-items="DropDowns.ModelList()"></select>
@section Scripts{ 
<script>
    $(function () {
        let model = $('#Model').children()
        $('#Make').change(function () {
            let make = $(this).val()
            if (make == 'Ford') {
                $('#Model').empty()
                $('#Model').append(model)
                $('#Model option').eq(4).remove()
                $('#Model option').eq(3).remove()
            } else if (make == 'Toyota') {
                $('#Model').empty()
                $('#Model').append(model)
                $('#Model option').eq(2).remove()
                $('#Model option').eq(1).remove()
            }
        })
    })
</script>
}
Related