MVC 4 Razor - 创建动态DropDownList

Jam*_*rpe 5 .net javascript c# asp.net-mvc razor

我正在尝试创建一个包含两个DropDownLists的视图.第二个DropDownList中可用的选项取决于用户在第一个中选择的内容.我将此数据传递给ViewBag中的视图,如下所示:

   List<SelectListItem> firstBoxChoices =  ViewBag.firstBoxChoices;
   Dictionary<string, List<SelectListItem>> secondBoxDict = ViewBag.secondBoxDict;
Run Code Online (Sandbox Code Playgroud)

第一个对象具有第一个DropDownList的选项.当用户选择其中一个时,我需要从我的Dictionary中获取第二个DropDownList的相应选择列表.我只是无法弄清楚如何实现这一目标.如果我在Javascript onchange()函数中获得第一个DropDownList的新选择,似乎没有任何方法可以将此值用作我的C#字典的键.

当然,我已经在网上看到了这个功能,所以我知道它必须以某种方式.我怎样才能做到这一点?

谢谢!

Jar*_*rga 8

有几种方法可以在不强制您将所有可能的数据项存储在模型中的情况下执行此操作,我的偏好是使用Javascript/JQuery.以下是国家/州级联下拉列表的示例:

用于在选择国家/地区时获取状态的Javascript:

<script type="text/javascript">
    function AppendUrlParamTokens(url, params) {

        for (var param in params) {
            if (params[param] == null) {
                delete params[param];
            }
        }

        return url + "?" + jQuery.param(params);
    }

    function OnCountriesChange(ddl) {
        jQuery.getJSON(AppendUrlParamTokens('@Url.Action("GetStates", "Data")', { countryId: ddl.options[ddl.selectedIndex].value }), function (result) {
            var target = jQuery('#states_ddl');
            target.empty();
            jQuery(result).each(function() {
                jQuery(document.createElement('option'))
                    .attr('value', this.Value)
                    .text(this.Text)
                    .appendTo(target);
            });
        });
    };
</script>
Run Code Online (Sandbox Code Playgroud)

国家下拉:

@Html.DropDownListFor(model => model.Country, new SelectList(Model.Countries, "Value", "Text", Model.PreviousCountrySelected), "(Select One)", new { id = "countries_ddl", onchange = "OnCountriesChange(this)" })
Run Code Online (Sandbox Code Playgroud)

州下拉:

Html.DropDownListFor(model => model.State,
                              Model.States != null
                                       ? new SelectList(Model.States, "Value", "Text", Model.PreviousStateSelected)
                                       : new SelectList(new List<SelectListItem>(), "Value", "Text"),
                              new { id = "states_ddl" })
Run Code Online (Sandbox Code Playgroud)

检索状态的控制器方法:

public ActionResult GetStates(short? countryId)
{
    if (!countryId.HasValue)
    {
        return Json(new List<object>(), JsonRequestBehavior.AllowGet);
    }

    var data = GetAllStatesForCountry(countryId.Value).Select(o => new { Text = o.StateName, Value = o.StateId });

    return Json(data, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是,在选择下拉列表1时,您使用ajax来检索第二个下拉列表的值.

编辑:忘记包含构建网址的实用工具方法