使用c# (Razor)获取下拉列表的selecteindex
本文关键字:下拉列表 selecteindex 获取 Razor 使用 | 更新日期: 2023-09-27 18:07:33
是否可以使用c# (Razor)在视图中获取下拉列表的selectedIndex ?例如,我可以根据使用Razor的另一个下拉列表的selecteindex填充第二个下拉列表吗?
@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>
当第一个下拉菜单发生变化时,您可以使用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);
}