更改MVC SelectList选择的值

时间:2013-07-30 09:09:31

标签: c# asp.net-mvc

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循环和另一个foreach循环之间改变计算机中的位。

然而,我得到true, false。这怎么可能远程可能?使用调试器,我看到'item'被正确解析并且{I}在我想要的项目上正确调用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");

2 个答案:

答案 0 :(得分: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中测试过,所以请玩它,看看你是否可以让它工作

答案 1 :(得分:0)

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

相关问题