问题描述
我知道我可以使用 SelectedListItem>
和 @Html.DropDownList("someID")
和 os on..
I know I can make a dropdown with a list of SelectedListItem>
and @Html.DropDownList("someID")
and os on..
我的问题是,如果您有 2 个下拉列表,而第二个下拉列表取决于第一个下拉列表中的所选项目,该怎么办?
My question is, what if you had 2 dropdowns, and the second dropdown depended on the selected item from the first dropdown?
你如何填充它?用JS?你会怎么做?您是否会使用另一个列表更改填充,更改整个下拉列表,或者每个下拉组合都有一个部分视图,因此只需用正确的下拉列表替换即可.
How do you populate it? With JS? How would you go about it?Would you change the populate with another list, change the whole dropdown or maybe have a partialview for each dropdown combination, so it's a matter of replacing with the right dropdown.
推荐答案
我添加了 NetFiddle 示例.作品这里
I have added NetFiddle example. Works here
我建议使用 jquery $.getJson()
填充第二个下拉列表而不刷新页面.你可以像下面的例子一样实现.
I would suggest to use jquery $.getJson()
to fill second dropdown without refresh to page. You can implement like following example.
//html
<select id="EventId" name="eventId">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
</select>
<label>Second</label>
<select id="SecondDropdown">
</select>
//jquery
$("#EventId").on("change", function(){
showValue($(this).val());
})
function showValue(val)
{
console.log(val);
$.getJSON('@Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#SecondDropdown").append("<option>"+ data[i] +"</option>")
}
})
}
//控制器
[HttpGet]
public JsonResult GetDropdownList(int? value)
{
List<string> yourdata = new List<string>();
if(value == 2)
{
yourdata.Add("option2a");
yourdata.Add("option2b");
yourdata.Add("option2c");
return Json(new { data = yourdata}, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { data = ""}, JsonRequestBehavior.AllowGet);
}
}
这篇关于MVC (5) 根据另一个填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!