2013-07-30 97 views
0
SelectList dropdown = DropDown; 
foreach (var item in dropdown) 
    { 
    var modelValue = property.GetValue(Model.FormModel); 
    if (String.Equals(item.Value, modelValue)) 
       { 
        item.Selected = true; 
        System.Diagnostics.Debug.WriteLine(item.Selected); 
       } 
    } 

foreach (var item in dropdown) 
     { 
     var modelValue = property.GetValue(Model.FormModel); 
     if (String.Equals(item.Value, modelValue)) 
      { 
        System.Diagnostics.Debug.WriteLine(item.Selected); 
       } 
     } 

在逻辑上,上面的代码应该输出存在或是true, true除非魔术磁场在一个foreach循环和另一个之间的计算机改变比特。改变MVC的SelectList选定值

但是,我得到了true, false。这如何远程可能?使用调试器,我看到'item'被正确解析,并且item.Selected = true在我想要的项目上正确调用。第二个循环仅用于调试目的。


这是我如何构建DropDown。我无法触及此代码,因为返回的下拉菜单应始终是通用的。

var prov = (from country in Service.GetCountries() 
     select new 
      { 
      Id = country.Id.ToString(), 
      CountryName = Localizator.CountryNames[(CountryCodes)Enum.Parse(typeof(CountryCodes), country.Code)], 
      }).Distinct().ToList().OrderBy(l => l.CountryName).ToList(); 
      prov.Insert(0, new { Id = String.Empty, CountryName = Localizator.Messages[MessageIndex.LabelSelectAll] }); 
    _customerCountrySelectionList = new SelectList(prov, "Id", "CountryName"); 
+0

显示你如何定义'DropDown'。 – YD1m

+0

完成!更新... – Saturnix

回答

2

如果您使用foreach遍历集合,则无法修改其内容。 因此第二迭代将访问相同的未修改列表...

使用LINQ直接创建“SelectListItems”的列表,然后分配列表使用您的代码dropdownhelper

from x in y where ... select new SelectListItem { value = ..., text = ..., selected = ... } 

...你可能要像

var modelValue = property.GetValue(Model.FormModel); 
IEnumerable<SelectListItem> itemslist = 
     (from country in Service.GetCountries() 
      select new SelectListItem { 
      { 
      value = country.Id.ToString(), 
      text = Localizator 
         .CountryNames[ 
          (CountryCodes)Enum 
             .Parse(typeof(CountryCodes), 
          country.Code) 
         ], 
      selected = country.Id.ToString().Equals(modelValue) 
      }).Distinct().ToList().OrderBy(l => l.text); 

创造的东西......还没有测试,在VS了,所以玩它,看看你能得到它的工作

+0

我从来没有使用过Linq(上面的代码的第二部分不是我写的),但我会尝试它。我可能需要一些时间... – Saturnix

+0

好像它工作!我遵循了你的建议,但是没有使用Linq。我想我会用工作代码编辑你的答案,以防其他人可能需要在没有Linq的情况下编辑SelectList。 – Saturnix

0

item.Selected = true;在第一个循环中设置为true。

+0

这就是代码的目的......问题是:为什么它在第二个循环中是错误的? – Saturnix