MVC 4剃刀 - 创建一个动态的DropDownList [英] MVC 4 Razor - Creating a dynamic DropDownList

查看:166
本文介绍了MVC 4剃刀 - 创建一个动态的DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个视图,它有两个DropDownLists。在第二个DropDownList中可用的选项取决于什么样的用户在第一次选择了。我通过这个数据,我在ViewBag观点如下:

I'm trying to create a view which has two DropDownLists. The options available in the second DropDownList depend upon what the user has selected in the first. I'm passing this data to my view in the ViewBag as follows:

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

的第一个对象具有用于第一个DropDownList的选择。当用户选择其中的一个,我需要的选择合适的列表从我的字典第二个DropDownList中。我只是无法弄清楚如何实现这一目标。如果我得到了新的选择在JavaScript的onchange()函数的第一个DropDownList的,似乎没有任何办法来使用这个值作为关键我的C#的字典。

The first object has the choices for the first DropDownList. When the user selects one of those, I need to get the appropriate list of choices for the second DropDownList from my Dictionary. I just can't figure out how to achieve this. If I get the new selection of the first DropDownList in a Javascript onchange() function, there doesn't seem to be any way to use this value as the key for my C# dictionary.

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

Of course, I've seen this functionality on the web so I know it must be possible somehow. How can I achieve this?

谢谢!

推荐答案

有这样做的几种方法不强迫你来存储所有在模型中可能出现的数据项,我的preference是使用JavaScript / JQuery的。这是一个国家/州级联的例子下拉:

There are a couple ways of doing this without forcing you to store all the possible data items in the model, my preference is to use Javascript/JQuery. Here is an example of a Country/State cascading drop down:

Java脚本用于获取国家在选择一个国家:

Javascript used to get states when a country is selected:

<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>

国家下拉列表:

Country dropdown:

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

状态下拉列表:

State dropdown:

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

控制器方法来检索状态:

Controller method to retrieve states:

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去找回你的第二个下拉菜单中的值。

The idea is that on selection of dropdown 1 you use ajax to go retrieve your second dropdown's value.

编辑:忘记了包括构造URL的实用方法

Forgot to include utility method for constructing urls

这篇关于MVC 4剃刀 - 创建一个动态的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆