【问题标题】:Html.DropDownListFor doesn't select correct valueHtml.DropDownListFor 没有选择正确的值
【发布时间】:2011-12-24 05:45:59
【问题描述】:

从包含国家/地区的 XML 文件生成 Selectlist (IEnumerable),将其与 DropDownListFor 一起使用不会设置模型中提供的选定值??

public static IEnumerable<SelectListItem> CountrySelectList()
    {
        var sRetVal = new List<SelectListItem>();
        string CachKey = "MVCXMLCountryList" + GetCulture();
        if (HttpContext.Current.Cache[CachKey] == null | 1 == 1)
        {
            string xmlFile = Path.Combine(HttpContext.Current.Server.MapPath("~"),      "Countries.xml");

            XmlDocument Doc = new XmlDocument();
            Doc.Load(xmlFile);
            foreach (XmlNode Node in    Doc.SelectNodes(String.Format("//Countries/language[@iso=\"{0}\"]/country", GetCulture())))
            {
                var tmpSelect = new SelectListItem();
                tmpSelect.Value = Node.Attributes["iso2"].InnerText.ToString();
                tmpSelect.Text = Node.Attributes["name"].InnerText;
                tmpSelect.Selected = false;
                sRetVal.Add(tmpSelect);
            }
            sRetVal.Sort(CountrySort);
            var prioritet = new string[] {"de","fo","se","no","dk"};
            switch (GetCulture())
            {
                case "dk": prioritet = new string[] {"de","fo","se","no","dk"}; break;
                default: prioritet = new string[] { "de", "se", "no", "dk", "gb" }; break;
            }

                foreach (string Country in (string[])prioritet)
                {
                    selectedCountry = Country;
                    var tmpSel = sRetVal.Find(FindCurrentSelected);
                    sRetVal.RemoveAt(sRetVal.FindIndex(FindCurrentSelected));
                    sRetVal.Insert(0, tmpSel);
                }
                //sRetVal[10].Selected = true;
            HttpContext.Current.Cache[CachKey] = sRetVal;
        }
        else
        {
            sRetVal = (List<SelectListItem>)HttpContext.Current.Cache[CachKey];
        }
        return (IEnumerable<SelectListItem>) sRetVal;
    }

两个都试过了:

@Html.DropDownListFor(model => model.Country, new SelectList(CommonHelpers.CountrySelectList(), "Value", "Text", Model.Country), "---Select---")

@Html.DropDownListFor(model => model.Country, CommonHelpers.CountrySelectList(), "---Select---")

有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc html-helper


    【解决方案1】:

    模型属性(国家/地区)和显式传入的 SelectList 需要具有不同的名称才能连接所选项目。当没有提供选定值时,浏览器默认为 SelectList 中的第一个元素。这是 DropDownList 助手的一个已知限制。 我正在完成一个 DDL 教程。您可以在http://code.msdn.microsoft.com/Using-the-DropDownList-67f9367d 获取完整的代码 给我发一封电子邮件,我会把教程发给你。Rick.Anderson[at]microsoft.com

    【讨论】:

    • 谢谢。已经查看了链接,但看不到我的代码在哪里失败。是否愿意从控制器提供 SleectList(带有 SELECTED 集),但它仍然无法正常工作?
    【解决方案2】:

    您需要将“国家/地区”值传递给您的方法,然后检查所选值

    public static IEnumerable<SelectListItem> CountrySelectList(string countryId)
    {
        var sRetVal = new List<SelectListItem>();
        // .......................         
        foreach (XmlNode Node in Doc.SelectNodes(String.Format("//Countries/language[@iso=\"{0}\"]/country", GetCulture())))
        {
            var tmpSelect = new SelectListItem();
            tmpSelect.Value = Node.Attributes["iso2"].InnerText.ToString();
            tmpSelect.Text = Node.Attributes["name"].InnerText;
            // Check for selected value
            tmpSelect.Selected = string.Equals(tmpSelect.Value, countryId);
            sRetVal.Add(tmpSelect);
        }
        //...................
        return (IEnumerable<SelectListItem>)sRetVal;
    }
    

    或者只是让新的助手为你做这件事。像这样的:

    public static IEnumerable<SelectListItem> SetSelected(this IEnumerable<SelectListItem> selectList, string selectedValue)
    {
        var newList = new List<SelectListItem>();
        var oldList = selectList.ToList();
        for (var i = 0; i < oldList.Count; i++)
        {
            var item = oldList[i];
            item.Selected = string.Equals(item.Value, selectedValue, StringComparison.CurrentCultureIgnoreCase);
            newList.Insert(i, item);
        }
        return newList;
    }
    

    这是用法:

    @Html.DropDownListFor(model => model.Country, CommonHelpers.CountrySelectList().SetSelected(model.Country), "---Select---")
    

    【讨论】:

    • 感谢您的回答!尝试在 SelectList 中设置 SELECTED 但它没有帮助(不管这样做的方法)?需要看懂下面的答案,看看有没有答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多