我正在尝试将动态元素数组绑定(bind)到 View 模型,其中 html 中可能缺少索引
例如与 View 模型
class FooViewModel
{
public List<BarViewModel> Bars { get; set; }
}
class BarViewModel
{
public string Something { get; set; }
}
和 html
<input type="text" name="Bars[1].Something" value="a" />
<input type="text" name="Bars[3].Something" value="b" />
<input type="text" name="Bars[6].Something" value="c" />
此时,bars 将为 null。我怎样才能让模型绑定(bind)器忽略任何丢失的元素?即上述内容将绑定(bind)到:
FooViewModel
{
Bars
{
BarViewModel { Something = "a" },
BarViewModel { Something = "b" },
BarViewModel { Something = "c" }
}
}
最佳答案
添加 .Index
作为您的第一个隐藏输入,以处理无序元素,如 Phil Haacked blog 中所述。帖子:
<input type="text" name="Bars.Index" value="" />
<input type="text" name="Bars[1].Something" value="a" />
<input type="text" name="Bars[3].Something" value="b" />
<input type="text" name="Bars[6].Something" value="c" />
关于asp.net - 在 asp.net mvc 中绑定(bind)缺少元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3564991/