使用c#(Razor)获取下拉列表的selectedIndex

时间:2015-08-11 18:56:16

标签: c# asp.net-mvc asp.net-mvc-4 razor

是否可以使用C#(Razor)获取视图中下拉列表的selectedIndex。例如,我可以根据使用Razor的另一个下拉列表的selectedIndex填充第二个下拉列表吗?

@model ViewModel

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

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

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

使用Javascript时,我也有点不对劲:

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

                }
            }
        </script>

1 个答案:

答案 0 :(得分:0)

当第一个下拉列表更改时,您可以使用ajax调用来执行此操作:

<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")

你的行动:

[HttpPost]
public ActionResult GetDropDown2Data(id id)
{

  //Here you get your data, ie Model2

   return Json(Model2, JsonRequestBehavior.AllowGet);
}