MVC3 Madness - 请帮助绑定包含的集合?
我在这里完全不知所措,找不到解决这个问题的方法。有人可以帮忙提供一些代码:
- 允许使用 [] 以便保存 @model 中包含的集合吗?
- 以某种方式从模型中映射/绑定包含的集合(我已阅读 Phil Haack 的集合绑定博客,但这不是传入的平面集合....我已经有一个模型 A 进来?
- 我也尝试过设置一个新的视图模型(包含下面的模型类 A 和 B),但我的模型在 httppost 中返回 null(即使我添加一个简单的字符串类型,如“Name”并绑定它......返回 null)。我确信存在我不知道的 AutoMapper 问题 我是mvc3
的新手,详细信息如下...
编辑视图:
@model MVC3.Models.A
// I need to save collection values but can't use [] here to setup model binding.
// I have read about mapping collections but I already have a model A that is getting passed in.
//
@Html.EditorFor(model => model.Bs[0].Val)
模型:
public class A
{
public A()
{
this.Bs = new HashSet<B>();
}
public int Name { get; set; }
public virtual ICollection<B> Bs { get; set; } // Can't change this to ILIst because of above HashSet
- }
public class B
{
public int Val { get; set; }
public virtual A A { get; set; }
}
I am totally at a loss here and can't find a solution to this problem. Can somebody please help provide some code to either:
- Allow [] to be used so as to save contained collection within a @model?
- Somehow map/bind a contained collection from within a model (I have read Phil Haack's Collection binding blog but this isn't a flat collection being passed in....I already have a model A coming in?
- I have also tried setting up a new view model (contains model classes A and B from below) but my model is coming back null in the httppost (even if I add a simple string type like "Name" and bind it...comes back null). I'm sure there AutoMapper issues that I am not aware of.
I'm a complete newbie with mvc3. Here are the details...
Edit View:
@model MVC3.Models.A
// I need to save collection values but can't use [] here to setup model binding.
// I have read about mapping collections but I already have a model A that is getting passed in.
//
@Html.EditorFor(model => model.Bs[0].Val)
Models:
public class A
{
public A()
{
this.Bs = new HashSet<B>();
}
public int Name { get; set; }
public virtual ICollection<B> Bs { get; set; } // Can't change this to ILIst because of above HashSet
- }
public class B
{
public int Val { get; set; }
public virtual A A { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的模型在视图模型中具有循环引用。这不是默认模型绑定器支持的场景。我建议您始终在视图中使用编辑器模板。示例:
模型:
控制器:
视图(
~/Views/Home/Index.cshtml
):将为 Bs 集合的每个元素呈现相应的编辑器模板(
~/Views/Home/ EditorTemplates/B.cshtml
):Your model has circular references in your view models. That's not a supported scenario by the default model binder. I would recommend you to always use editor templates in your views. Example:
Model:
Controller:
View (
~/Views/Home/Index.cshtml
):Corresponding editor template which will be rendered for each element of the Bs collection (
~/Views/Home/EditorTemplates/B.cshtml
):