gpt4 book ai didi

c# - 当集合中的第一个元素时,DropDownListFor 不选择值

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

我有模型,它有以下字段:

public List<SelectListItem> Months
{
get
{
return new List<SelectListItem>
{
new SelectListItem {Text = "111", Value = "1"},
new SelectListItem {Text = "222", Value = "2"}
};
}
}
public List<TestModel> ServiceTest { get; set; }

在哪里TestModel有一个字段:

public string Month { get; set; }

View 中的模型有 ServiceTest = new List<ServiceTest> {new ServiceTest {Month = "2"}};

现在,问题。为什么这样

@Html.DropDownListFor(m => m.ServiceTest[0].Month, Model.Months)

不选择第二个值。但是这个

@Html.DropDownListFor(m => m.ServiceTest[0].Month, new SelectList(Model.Months, "Value", "Text", Model.ServiceTest[0].Month))

工作正确。我真的不明白为什么第一个表达式不能正常工作。

最佳答案

这是因为 DropDownListFor 助手在绑定(bind)默认值时只支持简单的表达式。像 x => x.SomeProp 这样的东西。在第一个示例中,您使用的是复杂的 lambda 表达式(子属性索引器访问和另一个子属性)。

您的第二种方法是解决 helper 的这一限制的正确方法。

关于c# - 当集合中的第一个元素时,DropDownListFor 不选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20606666/

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