我正在尝试这样做:
这是我的ViewModel和Model:
public class OpeningYearViewModel
{
public int OpeningYearId { get; set; }
public string Description { get; set; }
public List<Grade> GradesList { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string Name { get; set; }
public int CurrencyId { get; set; }
public int Cost { get; set; }
}
这是我的控制器。我在这里构建
SelecList
并将其通过ViewBag
传递到视图OpeningYearViewModel viewmodel = new OpeningYearViewModel {
OpeningYearId = 1,
Description = "2015 - II",
GradesList = new List<Grade>
{
new Grade { GradeId = 1, Name = "Grade 1", CurrencyId = 1, Cost = 100 },
new Grade { GradeId = 2, Name = "Grade 2", CurrencyId = 2, Cost = 200 },
new Grade { GradeId = 3, Name = "Grade 3", CurrencyId = 2, Cost = 150 }
}
};
SelectList list = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "S/.", Value = "1"},
new SelectListItem { Text = "$", Value = "2"},
}, "Value" , "Text");
ViewBag.currencyList = list;
return View(viewmodel);
在我的视图中,我需要为GradesList上的每个项目添加一个DropDownListFor,所以我这样做:
@model Test.Models.OpeningYearViewModel
@for(int i = 0; i < Model.GradesList.Count; i++)
{
@Html.DropDownListFor(x => x.GradesList[i].CurrencyId, new SelectList(ViewBag.currencyList, "Value", "Text"))
@Model.GradesList[i].CurrencyId //This is just to know the CurrencyId on every item.
}
我正在正确渲染每个选择,但无法在页面加载中选择正确的选项:
render of view
可以做我想做的事情而做错了什么,或者DropDownListFor以不同的方式工作?
谢谢!
最佳答案
我不明白为什么会这样,但是您可以通过显式设置所选值来解决。这可以通过将Model.GradesList[i].CurrencyId
作为第四个参数传递给SelectList
的构造函数来完成:
@for(int i = 0; i < Model.GradesList.Count; i++)
{
@Html.DropDownListFor(x => x.GradesList[i].CurrencyId,
new SelectList(ViewBag.currencyList, "Value", "Text", Model.GradesList[i].CurrencyId))
}