将DropDownListFor与ViewModel上的列表绑定 [英] Bind DropDownListFor with List on ViewModel

查看:120
本文介绍了将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))
}

这篇关于将DropDownListFor与ViewModel上的列表绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆