Get selectedIndex of dropdown using c# (Razor)

1.5k Views Asked by At

Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?

@model ViewModel

<select id="dropdown1">
//Options
</select>

<select id="dropdown2">
//Options
</select>

@if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}

When using Javascript, I am a little off as well:

            <script>
            if (dropdown1.selectedIndex === 3)
            {
                @foreach (var item in Model)
                {

                }
            }
        </script>
1

There are 1 best solutions below

2
Alan Macgowan On

You can do it using a ajax call when the first dropdown changes:

<script type="text/javascript">
function getDropDown2Data(id) {
    $.ajax({
        url: '@Url.Action("GetDropDown2Data", "YourController")',
        data: { Id: id },
        dataType: "json",
        type: "POST",
        success: function (data) {
            var items = "";
            $.each(data, function (i, item) {
                items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
            });

            $("#dropDown2").html(items);
        }
    });
}

$(document).ready(function () {
    $("#dropDown2").change(function () {
        var id = $("#dropDown2").val();
        getDropDown2Data(id);
    });
});
</script>


 @Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")

 @Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")

And you action:

[HttpPost]
public ActionResult GetDropDown2Data(id id)
{

  //Here you get your data, ie Model2

   return Json(Model2, JsonRequestBehavior.AllowGet);
}