在ASP.Net Core MVC中,如果ViewModel包含一个列表的对象属性,可能会遇到无法绑定的问题。这种问题通常会出现在ViewModel中包含复杂的嵌套对象属性用于表单提交的情况下。
解决此问题的方法是使用特定的属性名称前缀。 在表单中提交数据时,ASP.NET Core MVC将使用该前缀为视图模型映射属性。
假设我们有如下的ViewModel:
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List Children { get; set; }
}
public class ChildModel
{
public string ChildName { get; set; }
public int Age { get; set; }
}
为了使此ViewModel能够成功绑定,我们需要在属性名称前面加上一个特定的前缀。 例如,我们可以使用“Children”作为前缀。
在HTML中,我们可以按照以下方式命名输入字段:
......
在提交数据时,ASP.NET Core MVC自动将输入字段中的值绑定到MyViewModel实例中的ChildModels列表属性中,前提是使用正确的名称前缀。
这样,我们就可以成功绑定具有列表对象属性的复杂ViewModel。