【问题标题】:MVC3 Madness - Please help binding contained collection?MVC3 Madness - 请帮助绑定包含的集合?
【发布时间】:2011-10-24 05:38:46
【问题描述】:

我在这里完全不知所措,无法找到解决此问题的方法。有人可以帮忙提供一些代码吗:

  • 是否允许使用 [] 以便将包含的集合保存在 @model 中?
  • 以某种方式从模型中映射/绑定包含的集合(我已阅读 Phil Haack 的集合绑定博客,但这不是传入的平面集合......我已经有一个模型 A 进来了?
  • 我还尝试设置一个新的视图模型(包含下面的模型类 A 和 B),但我的模型在 httppost 中返回 null(即使我添加了一个简单的字符串类型,如“名称”并绑定它。 ..返回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; }
       }

【问题讨论】:

  • 代替model.Bs[0].Val试试model.Bs.First().Val
  • 我试过 First().Val 并且它没有绑定/映射。
  • 嗨 Ankur,不,没有错误。只是根本没有绑定。谢谢!

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2


【解决方案1】:

您的模型在视图模型中有循环引用。这不是默认模型绑定器支持的场景。我建议您始终在视图中使用编辑器模板。示例:

型号:

public  class A
{
    public int Name { get; set; }
    public virtual ICollection<B> Bs { get; set; }
}

public class B
{
    public int Val { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new A
        {
            Name = 123,
            Bs = new[]
            {
                new B { Val = 1 },
                new B { Val = 2 },
                new B { Val = 3 },
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(A a)
    {
        // The Bs collection will be properly bound here
        return View(a);
    }
}

查看(~/Views/Home/Index.cshtml):

@model A

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
    </div>
    @Html.EditorFor(x => x.Bs)
    <button type="submit">OK</button>
}

将为 Bs 集合的每个元素呈现相应的编辑器模板 (~/Views/Home/EditorTemplates/B.cshtml):

@model B
<div>
    @Html.LabelFor(x => x.Val)
    @Html.EditorFor(x => x.Val)
</div>

【讨论】:

  • 你好,达林!非常感谢您的回复和示例。让我试试这个。只是好奇,所以我要做的就是创建 B.cshtml 并调用 @Html.EditorFor(x => x.Bs) 自动调用 B.cshtml?
  • @Mariah,是的。编辑器模板使用您需要遵守的命名约定。例如,如果您有ICollection&lt;SomeType&gt;,则编辑器模板必须命名为SomeType.cshtml,并且位于~/Views/CurrentController/EditorTemplates~/Views/Shared/EditorTemplates,具体取决于您是否要在不同的控制器之间重用它。
  • 你摇滚!我确实得到了编辑器模板,并且 B 值集合最终在输入 HttpPost ActionResult 时绑定。耶!再次非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2011-04-26
  • 2011-07-12
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多