Html.DropDownListFor没有选择正确的值

时间:2011-12-24 05:46:00

标签: asp.net-mvc html-helper

从包含国家/地区的XML文件生成选择列表(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---")

任何想法?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您需要将“Country”值传递给您的方法,然后检查所选值

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