6

我有以下代码

public class TestModel
{
   public int TestId1 { get; set; }
   public int TestId2 { get; set; }
   public int TestId3 { get; set; }
   public List<TestSubModel> SubMods { get; set; }

   public IEnumerable<SelectListItem> SelectListItems { get; set; }
}

public class TestSubModel
{
   public string ItemId { get; set; }
}

public class HomeController : Controller
{
   public ActionResult Index()
   {
      var m = new TestModel
      {
         TestId1 = 1,
         TestId2 = 2,
         TestId3 = 3,
         SelectListItems = new List<SelectListItem> { 
                         new SelectListItem { Value = "1", Text = "Item 1" },
                         new SelectListItem { Value = "2", Text = "Item 2" },
                         new SelectListItem { Value = "3", Text = "Item 3" }
                      },
         SubMods = new List<TestSubModel> { 
                         new TestSubModel { ItemId = "1" },
                         new TestSubModel { ItemId = "2" },
                         new TestSubModel { ItemId = "3" }
                      }
      };
      return View(m);
   }
}

和视图:

@model MvcApplication2.Controllers.TestModel

@using (Html.BeginForm())
{
   <ul>
      <li>Test1 Value @Model.TestId1 : @Html.DropDownListFor(i => i.TestId1, Model.SelectListItems)</li>
      <li>Test2 Value @Model.TestId2 : @Html.DropDownListFor(i => i.TestId2, Model.SelectListItems)</li>
      <li>Test3 Value @Model.TestId3 : @Html.DropDownListFor(i => i.TestId3, Model.SelectListItems)</li>
      <li></li>
      @for (var index = 0; index < Model.SubMods.Count(); index++)
      {
         <li>SubModel @index: value @Model.SubMods[index].ItemId
                      @Html.DropDownListFor(i => i.SubMods[index].ItemId, Model.SelectListItems)</li>
      }
   </ul>
}

输出是:

结果

我期望的是第 1 项、第 2 项和第 3 项被选中两次。为什么 Razor 没有在 for 循环中选择正确的项目?

这也不起作用:

@Html.DropDownListFor(i => i.SubMods[index].ItemId, 
                      new SelectList(Model.SelectListItems, "Value", "Text"))

但这确实:

@Html.DropDownListFor(i => i.SubMods[index].ItemId, 
                      new SelectList(Model.SelectListItems, "Value", "Text", Model.SubMods[index].ItemId))

我真的不想每次都创建一个新的选择列表。这是一个错误还是我错过了什么?

从 2010 年就看到了这个问题,但没有答案。

4

0 回答 0