ASP.NET MVC多个组合框

时间:2011-02-04 11:42:26

标签: asp.net-mvc combobox

我想有一个小例子屏幕应该有两个组合。第一个应显示国家/地区表中国家/地区的名称,在组合中选择国家/地区名称后,下一个组合应显示为地区名称。

国家/地区表格结构:

Country Name,
Country Id

区表结构。

District id
Country id
District name

任何人都可以帮助我?

2 个答案:

答案 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,并在服务器端填充第二个组合,具体取决于第一个组合的选定值。