如何在级联下拉列表中显示所选值?

时间:2009-04-13 16:00:05

标签: .net asp.net asp.net-mvc

我希望在编辑视图中为选定值扩展以下代码。 以国家为例 - >国家 - >城市。

我有脚本CascadingDropDownList.js:

function bindDropDownList(e, targetDropDownList) 
{
    var key = this.value;
    var allOptions = targetDropDownList.allOptions;
    var option;
    var newOption;
    targetDropDownList.options.length = 0;

    for (var i=0; i < allOptions.length; i++) 
    {
        option = allOptions[i];
        if (option.key == key) 
        {
            newOption = new Option(option.text, option.value);
            targetDropDownList.options.add(newOption);
        }
    }
}

我有一个助手类:

public static class JavaScriptExtensions
{
    public static string CascadingDropDownList(this HtmlHelper helper, string name, string associatedDropDownList)
    {
        var sb = new StringBuilder();

        // render select tag
        sb.AppendFormat("<select name='{0}' id='{0}'></select>", name);
        sb.AppendLine();

        // render data array
        sb.AppendLine("<script type='text/javascript'>");
        var data = (CascadingSelectList)helper.ViewDataContainer.ViewData[name];
        var listItems = data.GetListItems();
        var colArray = new List<string>();
        foreach (var item in listItems)
            colArray.Add(String.Format("{{key:'{0}',value:'{1}',text:'{2}'}}", item.Key, item.Value, item.Text));
        var jsArray = String.Join(",", colArray.ToArray());
        sb.AppendFormat("$get('{0}').allOptions=[{1}];", name, jsArray);
        sb.AppendLine();
        sb.AppendFormat("$addHandler($get('{0}'), 'change', Function.createCallback(bindDropDownList, $get('{1}')));", associatedDropDownList, name);
        sb.AppendLine();
        sb.AppendLine("</script>");

        return sb.ToString();

    }
}

public class CascadingSelectList
{
    private IEnumerable _items;
    private string _dataKeyField;
    private string _dataValueField;
    private string _dataTextField;

    public CascadingSelectList(IEnumerable items, string dataKeyField, string dataValueField, string dataTextField)
    {
        _items = items;
        _dataKeyField = dataKeyField;
        _dataValueField = dataValueField;
        _dataTextField = dataTextField;
    }

    public List<CascadingListItem> GetListItems()
    {
        var listItems = new List<CascadingListItem>();
        foreach (var item in _items)
        {
            var key = DataBinder.GetPropertyValue(item, _dataKeyField).ToString();
            var value = DataBinder.GetPropertyValue(item, _dataValueField).ToString();
            var text = DataBinder.GetPropertyValue(item, _dataTextField).ToString();
            listItems.Add(new CascadingListItem(key, value, text));
        }
        return listItems;
    }
}
public class CascadingListItem
{
    public CascadingListItem(string key, string value, string text)
    {
        this.Key = key;
        this.Value = value;
        this.Text = text;
    }

    public string Key { get; set; }
    public string Value { get; set; }
    public string Text { get; set; }
}

1 个答案:

答案 0 :(得分:2)

我已经实现了它。选择的值在隐藏归档中。

确保你的控制器方法返回带有两个字段的json对象。

<script type="text/javascript">

var ddlCountry;
var ddlStateID;

function pageLoad() {
    ddlStateID = $get("StateID");
    ddlCountry = $get("CountryID");
    $addHandler(ddlCountry, "change", bindOptions);
    bindOptions();
}
function bindOptions() {
    ddlStateID.options.length = 0;
    var CountryID = ddlCountry.value;
    var stateSelected = document.getElementById('StateSelected').value;
    if (CountryID) {
        var url = "/Student/States/" + CountryID;
        $.getJSON(url, null, function(data) {
            $("#StateID").empty();
            $.each(data, function(index, optionData) {
                if (stateSelected == optionData.ID) {
                    $("#StateID").append("<option value='"
                    + optionData.ID
                    + "' selected>" + optionData.Name
                    + "</option>");
                }
                else {
                    $("#StateID").append("<option value='"
                    + optionData.ID
                    + "'>" + optionData.Name
                    + "</option>");
                };
            });
        });
    };
}

<强> ADDED 控制器(我的网址是学生/州,即在学生控制器中我放下以下代码)

public ActionResult States(int id)
    {
        var states = db.states.Select(s => new { ID = s.ID, Name = s.Name }).OrderBy(s=>s.Name).ToList();
        return Json(states);
    }

您可以返回任意数量的字段,但如果其中任何字段具有空值,则它不会在json对象中转换。我不确定这一点但是当我返回整个状态对象时它无法正常工作。那时状态表有一个名为deletedby的字段,它包含空值!但是,当我只返回两个“必需”字段时,它才能正常工作!