我想有一个小例子屏幕应该有两个组合。第一个应显示国家/地区表中国家/地区的名称,在组合中选择国家/地区名称后,下一个组合应显示为地区名称。
国家/地区表格结构:
Country Name,
Country Id
区表结构。
District id
Country id
District name
任何人都可以帮助我?
答案 0 :(得分:5)
这有点容易......
第一次下拉很容易,只需通过模型中的IEnumerable
即可。
第二次下拉列表非常简单但只需要更多代码:
您需要做的就是调用方法并发送第一个下拉列表的值,然后在您的方法中,只需调用数据库并返回JsonResult
示例:的
<select id="dropdown1">
<option value="" selected="true">Select country</option>
<% foreach(var country in Model.Countries) { %>
<option value="<%= country.Id %>"><%= country.Name %></option>
<% } %>
</select><br/>
<select id="dropdown2"></select>
在页面末尾
<script>
$(document).ready( function() {
$("#dropdown1").bind("change", function() {
// everytime the value of the dropdown 1 is changed, do this:
var countryId = $("#dropdown1").val();
$.get("/country/getDistricts", { 'country' : countryId }, function(data) {
$("#dropdown2").empty(); // clear old values if exist
var options = "";
for(i = 0; i < data.length; i++) { // build options
options += ("<option value='" + data[i].districtId + "'>" + data[i].districtName + "</option>");
}
$("#dropdown2").append(options);
});
});
});
</script>
在country
控制器
public ActionResult getDistricts(string country)
{
List<Districts> districts = dbRepository.GetDistrictsByCountryId(country);
return Json(districts, JsonRequestBehavior.AllowGet);
}
答案 1 :(得分:-2)
有两种可能的方法来实现这一目标。
将所有组合放在html中并使用javascript在第一个组合中选择时更改第二个组合的内容。
或者在第一个组合上设置AutoPostback,并在服务器端填充第二个组合,具体取决于第一个组合的选定值。