我有以下代码
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))
我真的不想每次都创建一个新的选择列表。这是一个错误还是我错过了什么?
我看到this question from 2010但没有回答。