gpt4 book ai didi

c# - 将 DropDownListFor 与 ViewModel 上的列表绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:26 26 4
gpt4 key购买 nike

我正在尝试这样做:

这是我的 ViewModel 和模型:

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; }
}

这是我的 Controller 。我在这里构建了一个SelecList,并通过ViewBag

传递给 View
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);

在我的 View 中,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))
}

关于c# - 将 DropDownListFor 与 ViewModel 上的列表绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com