将DropDownListFor与ViewModel上的列表绑定

将DropDownListFor与ViewModel上的列表绑定

问题描述:

我正在尝试这样做:

这是我的ViewModel和模型:

This is my ViewModel and 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

This is my Controller. I build a SelecList here and pass it to the view through the 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,所以我可以这样做:

And in my View I need a DropDownListFor for every item on GradesList so I do this:

@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.
}

我正在正确渲染每个选择,但是无法在页面加载时选择正确的选项: 渲染视图

I'm getting every select correctly rendered, but I can't get the correct option selected on the page load: render of view

有可能做我想做的事情,而我做错了什么,或者DropDownListFor以不同的方式工作?

It is possible to do what I'm trying to do and I'm doing something wrong, or DropDownListFor works in a different way?

谢谢!

我不明白为什么会这样,但是您可以通过显式设置所选值来解决.这可以通过将Model.GradesList[i].CurrencyId作为第四个参数传递给SelectList的构造函数来完成:

I can't understand why this is happening but you can workaround it by setting explicitly the selected value. This can be done by passing Model.GradesList[i].CurrencyId as fourth parameter to the SelectList's constructor:

@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))
}