MVC模型绑定EF 6缺少父级参考

时间:2015-12-28 18:12:03

标签: asp.net-mvc entity-framework-6

我有一个带有集合的对象。我正在将模型传递给视图,并在发布时集合在那里,但是引用(包含对象Id)不在那里,导航属性为null。

模型

  public class Order
    {
         public int OrderId { get; set;}
         public List<OrderItem> OrderItems { get; set;}
    }

public class OrderItem 
{
     public int OrderItemId { get; set; }
     public int OrderId { get; set; }
     public int SomeOtherValue { get; set; } 
}

查看:

@model Order
<h2>Edit Form</h2>
@using (Html.BeginForm())
{
       @Html.HiddenFor(m => m.OrderId)

       //Some other form fields for the order...

         @for (int i = 0; i < Model.OrderItems.Count; i++)
         {
             @Html.TextBoxFor(x => Model.OrderItems[i].SomeOtherValue)
         }
         <input type="submit" value="Submit"/>
}

当我提交表单时,模型被正确绑定并且while调试我可以看到子OrderItems填充了更新的信息。但是,每个OrderItem上的OrderId都设置为0.

控制器

public ActionResult Edit(Order myOrder)
        {
             myOrder.OrderItems.Count(); // These are populated and the edited values are there. 

             myOrder.OrderItem[0].Order; // this is null (all order items)
             myOrder.OrderItem[0].OrderId; // this is set to 0 (all order items) 

            //...more stuff and return view. 
        } 

解决此问题的最佳方法是什么?有没有办法确保每个OrderItem在发布表单时都有对订单的引用?我希望在尝试保存对象时,我可以避免在控制器中手动考虑关联。

1 个答案:

答案 0 :(得分:1)

您应该为这些字段添加隐藏的输入。检查代码bolow:

...

@for (int i = 0; i < Model.OrderItems.Count; i++)
{
    @Html.HiddenFor(x => Model.OrderItems[i].OrderId)
    @Html.HiddenFor(x => Model.OrderItems[i].Order)

    @Html.TextBoxFor(x => Model.OrderItems[i].SomeOtherValue)
}

...