开发者

ASP.Net MVC View Model > Model Problem when calling UpdateModel

I'm having a problem that I could use some assistance with. I have an MVC 3 application that I am trying to fetch the form values for when posting back an Edit view but I'm obviously going about this wrong.

I have 3 tables with Entity Framework objects mapped to them. A Requestor can have an Order which can in turn have multiple OrderDetails

I have also created View Models for each of these entities and I also have created a strongly typed View called Edit which shows all the information and I populate the ViewModels with the following code - this all works fine its just for background information:

 //Grab the Requestor and corresponding order from the database
        var requestors = from r in db.Requestors
                         where r.RequestorID == id
                         join o in db.Orders on r.RequestorID equals o.RequestorID
                         select
                         new RequestorViewModel
                         {
                             RequestorID = r.RequestorID,
                             FirstName = r.FirstName,
                             LastName = r.LastName,
                             AddressStreet = r.AddressStreet,
                             AddressNumber = r.AddressNumber,
                             AddressCity = r.AddressCity,
                             AddressPostalCode = r.AddressPostalCode,
                             AddressProvince = r.AddressProvince,
                             Individual = r.Individual,
                             Organization = r.Organization,
                             PhoneNumber = r.PhoneNumber,
                             Email = r.Email,
                             Comment = r.Comment,
                             Order = new OrderViewModel
                             {
                                 OrderID = o.OrderID,
                                 TotalPamp开发者_如何学Chlets = o.TotalPamphlets,
                                 OrderCompletionDate = o.OrderCompletionDate,
                                 OrderDate = o.OrderDate,
                                 DateRequired = o.DateRequired
                             }
                         };

        RequestorViewModel requestor = requestors.Single<RequestorViewModel>();

        //Get the OrderDetails associated with the Order
        var orderdetails = from od in db.OrderDetails
                           where od.OrderID == requestor.Order.OrderID
                           select new OrderDetailViewModel
                           {
                               OriginalQuantity = od.OriginalQuantity,
                               UpdatedQuantity = od.UpdatedQuantity,
                               PamphletID = od.PamphletID
                           };

        requestor.Order.OrderDetails = orderdetails.ToList<OrderDetailViewModel>();

        return requestor;

My issue is when I attempt to update the database the only thing that updates is the Requestor Information.

My Edit Action looks as follows:

    [HttpPost]
    public ActionResult Edit(int ID, FormCollection formValues)
    {

        var query = from r in db.Requestors where r.RequestorID == ID select r;
        var req = query.SingleOrDefault();

        UpdateModel(req);
        db.SaveChanges();

        return View("Index");
    }

And a sample of my Edit View is below: ![Edit View][2]

For the Requestor and Order sections I am using the default template generated by Visual Studio and the editors look like this:

Requestor: @Html.EditorFor(model => model.FirstName)

Order: @Html.EditorFor(model => model.Order.OrderCompleted)

In my OrderDetails Section I am naming my controls with the following convention (they are in a loop (shortened for brevity)

 @foreach (var od in Model.Order.OrderDetails) {
    int i = 0;
@Html.TextBox("OrderDetails[" + i + "].OriginalQuantity", od.OriginalQuantity)
i++
}

When I look at the Form Collection the keys for for Requestor, Order and Orderdetail look as follows (some examples as I can't post a screen shot):

[1]RequestorID [17]Order.OrderCompleteed [22]OrderDetails[0].OriginalQuantity

Is it due to me not explicitly converting the OrderViewModel and OrderDetailViewModel to their respective EF entities? Or is it something else I am doing all wrong? Any help is greatly appreciated.

Jason


You said you have 3 tables with Entity Framework objects mapped to them. I would recommend creating associations between the three entities. You need to create an association on an entity if you want EF to attach the associated entity, so you could potentially have an association on both tables (back and forth).

Having associations on both tables is fine if you are doing server binding, but if you are doing Ajax binding there are sometimes problems related to circular references. Once you create associations then you can include entities and EF will manage doing joins where needed and updating data.

You can open your EF using an XML editor, but you don't need to; I just grabbed this from the XML editor to easily paste it here and give you a visual of what is needed. This creates only two associations one from requestor to order and one from order to order_item, use your foreign key values, the visual studio painter makes it simple.

 // one to many association between order and order_line
 <Association Name="FK_xxx">
      <End Role="order" Type="LINKDIRModel.Store.order" Multiplicity="1" />
      <End Role="order_line" Type="LINKDIRModel.Store.order_line" Multiplicity="*" />
      <ReferentialConstraint>
        <Principal Role="order">
          <PropertyRef Name="order_line" />
        </Principal>
        <Dependent Role="order_line">
          <PropertyRef Name="order_id" />
        </Dependent>
      </ReferentialConstraint>
  </Association>

 // controller code... for delete int order lines and updating order
 [HttpPost, ActionName("OrderDelete")]
 [GridAction]
 public ActionResult DeleteRequestor(int id)
 {
     // get order from EF along with all order_items.
     order myOrder = db.order.Include("order_line").Single(l => l.requestor_id == id);

     // We can delete a few order_lines and update the order easily
     List<order_line> myLines = 
        db.order.order_line.Where(o => o.order_id == id && o.order_amt == 1.00).ToList();

     // update the order
     MyOrder.order_comment = "deleted all the items with price of one dollar!";
     MyOrder.order_total = MyLines.Take(myLines.Count()).Sum(e => e.order_line_amt);
     MyOrder.DeleteObject(myLines);

     // save changes.
     db.SaveChanges();

    return View(new GridModel(db.requestor));
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜