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

时间:2022-02-11 07:42:30

I want extension of the following code for selected value in edit view. take a case of country -> state -> city.

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

i have script CascadingDropDownList.js:

我有脚本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);
        }
    }
}

and I have a helper class:

我有一个帮助类:

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 个解决方案

#1


I have achieved it. Where selected value is in Hidden Filed.

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

And make sure that your controller method returns json object with two fields.

并确保您的控制器方法返回带有两个字段的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 controller (My url is student/state i.e. in student controller I put following code)

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

You can return any number of fields but if any of them will have a null value then it will not converted in json object. I am not sure about this but it wasn't working when I return whole state object. At that time states table was having field called deletedby and it was containing null values!. But when I return only two 'needed' fields then it is working properly!

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

#1


I have achieved it. Where selected value is in Hidden Filed.

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

And make sure that your controller method returns json object with two fields.

并确保您的控制器方法返回带有两个字段的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 controller (My url is student/state i.e. in student controller I put following code)

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

You can return any number of fields but if any of them will have a null value then it will not converted in json object. I am not sure about this but it wasn't working when I return whole state object. At that time states table was having field called deletedby and it was containing null values!. But when I return only two 'needed' fields then it is working properly!

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