MVC 4 Razor-创建动态DropDownList

詹姆斯·哈珀

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

   List<SelectListItem> firstBoxChoices =  ViewBag.firstBoxChoices;
   Dictionary<string, List<SelectListItem>> secondBoxDict = ViewBag.secondBoxDict;

第一个对象具有第一个DropDownList的选项。当这些用户选择一个,我需要的选择适当的列表从我的字典第二个DropDownList中。我只是不知道如何实现这一目标。如果我在Javascript onchange()函数中获得了第一个DropDownList的新选择,则似乎没有任何方法可以将此值用作我的C#字典的键。

当然,我已经在网络上看到了此功能,所以我知道一定可以实现。我该如何实现?

谢谢!

雅加

有两种方法可以执行此操作,而不会强迫您在模型中存储所有可能的数据项,我的首选是使用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>

国家下拉列表:

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

状态下拉列表:

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" })

控制器状态检索方法:

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);
}

这个想法是,在选择下拉列表1时,您可以使用ajax来获取第二个下拉列表的值。

编辑:忘记包括用于构造URL的实用程序方法

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章