C# 将DropDownListFor与ViewModel上的列表绑定
我正在尝试这样做: 这是我的ViewModel和模型:C# 将DropDownListFor与ViewModel上的列表绑定,c#,asp.net-mvc,html.dropdownlistfor,viewbag,asp.net-mvc-viewmodel,C#,Asp.net Mvc,Html.dropdownlistfor,Viewbag,Asp.net Mvc Viewmodel,我正在尝试这样做: 这是我的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 GradeI
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; }
}
在我看来,我需要一个DropDownList,用于GradesList上的每个项目,所以我这样做:
@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.
}
@model Test.Models.OpeningYearViewModel
@对于(int i=0;ix.GradesList[i].CurrencyId,新选择列表(ViewBag.currencyList,“值”,“文本”))
@Model.GradesList[i].CurrencyId//这只是为了知道每个项目的CurrencyId。
}
我正在正确呈现每个选择,但无法在页面加载中选择正确的选项:
有可能做我想做的事情,但我做错了什么,或者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))
}
for(int i=0;i因为,DropDownListFor在循环中用于生成索引输入;因此,将生成名为“GradeList[0].CurrencyId”、“GradeList[1].CurrencyId”的生成输入控件……由于此框架无法获取反射中的值以供选择,因此不会绑定选择列表中的选定值。这就是为什么必须使用以下SelectList构造函数来设置所选值的原因
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
但是,如果您的DropDownListFor绑定到一个简单的表达式,如
@Html.DropDownListFor(model => model.CurrencyId, new SelectList(ViewBag.Items, "Value", "Text"))
然后选择将自动工作。这是在循环中使用
DropDownListFor()
的一个不幸的限制(在CodePlex上有过几次报告)。请注意,在您的代码中,您首先创建列表
,然后从中创建一个相同的IEnumerable
(这就是选择列表
的含义),然后在客户端上第三次再次执行所有操作(执行三次有点毫无意义)@StephenMuecke Good call。我对MVC有点陌生,所以我遵循了一个(糟糕的)教程。现在我正在处理对象列表,然后在视图上创建SelectList。谢谢,这就成功了。非常感谢。对于我的情况来说,DropDownListFor似乎有点有限。
@Html.DropDownListFor(model => model.CurrencyId, new SelectList(ViewBag.Items, "Value", "Text"))