Model的Child Collection始终为Null

时间:2012-12-18 20:54:22

标签: asp.net-mvc-4

我似乎无法理解ASP.MVC 4和Code First绑定中的子集合。当涉及子集合时,我总是得到模型对象为null的错误。我甚至无法检查子集合是否为null,因为模型为空。

我已经在控制器中验证了如果我创建了一个Batch对象并为其添加了步骤,那么它将会起作用。

我确定这很简单,但我无法弄清楚。

以下是我的目标:

public class Batch
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Details { get; set; }
    public virtual ICollection<Step> Steps { get; set; }
}
public class Step
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual int Days { get; set; }
    public virtual Batch Batch { get; set; }
}

这是我的控制器动作:

    [Authorize]
    public ActionResult Create()
    {
        return View();
    }

以下是我的观点:

@model BC.Models.Batch

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Batch</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Details)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Details)
            @Html.ValidationMessageFor(model => model.Details)
        </div>

        <div>
            <h3>Steps</h3>
            // Here is where I get a error that model is null
            @if(model.Steps != null)
            {
                foreach(var item in model.Steps)
                {
                    @Html.EditorFor(model => item)
                }
            }
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

1 个答案:

答案 0 :(得分:3)

实例化您的模型并将其传递给视图。

public ActionResult Create()
        {
            var model = new Batch();
            return View(model);
        }

这将解决视图中null模型的NullReference异常。

但是,当您到达Psot操作时,Steps(Batch中的集合)可能为null。要解决这个问题,请在构造函数中新建集合,如下所示:

public class Batch
    {
        public Batch()
        {
            Steps = new Collection<Step>();
        }
        public virtual int Id { get; set; }
        public virtual string Title { get; set; }
        public virtual string Details { get; set; }
        public virtual ICollection<Step> Steps { get; set; }
    }