【发布时间】:2013-01-05 21:34:23
【问题描述】:
我在编辑模型时遇到问题,该模型集合了链接的其他模型。 我正在使用带有模型类的强类型视图:
public class GroupViewModel
{
public GroupViewModel()
{
Group = new Group();
Sections = new List<Section>();
}
public Group Group { get; set; }
public IEnumerable<Section> Sections { get; set; }
}
在控制器的 Edit 方法中,我用正确的数据填充两个字段并将其传递给视图。视图正确显示我的视图模型,出现多选并填充传递的数据,组也是如此。
但是在我将它发送回表单提交后,我在 ModelState 中得到一个错误,类似于“从类型 'System.String' 到类型 'Myapp.Models.Section' 的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。"
ASP.NET 是正确处理子集合还是我需要使用旧的 FormCollection 来处理它?
UPD:由于Section是类,可能应用程序无法将解析的int转换为Section,并且可能无法从客户端获取某些字段(实际上,多选仅使用Id和Name,但省略了其他字段)?
UPD1:作为临时解决方案,我将代码更改为:
public class GroupViewModel
{
public GroupViewModel()
{
Group = new Group();
Sections = new List<Section>();
}
public Group Group { get; set; }
public IEnumerable<int> SectionsIds { get; set; } //here
public IEnumerable<Section> SectionsDS { get; set; } //as here
}
在视图中我将其绑定为:
@Html.ListBoxFor(x => x.SectionIds,
new MultiSelectList(Model.SectionsDS, "Id", "Name"));
在检索视图模型后同步 2 个集合 - 手动虚拟导航和 ID。
【问题讨论】:
标签: asp.net asp.net-mvc-4 model-binding