简体   繁体   中英

Edit order details in ASP.NET MVC

The standard way to edit a record in ASP.NET MVC is the following:

//
// GET: /Movies/Edit/5
public ActionResult Edit(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

//
// POST: /Movies/Edit/5
[HttpPost]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

The problem is that I need to edit order details (1 order, many details) and therefore based on two IDs (the order and the product ones). It does not work (I cannot get an OrderDetail item as action parameter). How can I solve this problem?

Thanks.

//
// GET: /Orders/EditDetails
public ActionResult EditDetails(int id, string productID)
{
   OrderDetail od = GetOrderDetail(id, productID);

   return View(od);
}

//
// POST: /Orders/EditDetails
[HttpPost]
public ActionResult EditDetails(OrderDetail od)
{
   if (ModelState.IsValid)
   {
      context.Entry(od).State = EntityState.Modified;
      context.SaveChanges();
      return RedirectToAction("Index");
   }
   return View(od);
}

EDIT: Here is the code requested by Shimmy:

@using (Html.BeginForm("EditDetails", "Orders", FormMethod.Post))
{
   @Html.LabelFor(m => m.quantity)
   @Html.TextBoxFor(m => m.quantity)

   @Html.LabelFor(m => m.productID)
   @Html.DropDownListFor(m => m.productID, new SelectList((IEnumerable)ViewBag.productList, "productID", "fullProductName"))

   @Html.HiddenFor(model => model.orderID)
}

Make sure the OrderDetail.Id itself as well as the OrderDetail.OrderId and the OrderDetail.MovieId properties are all present in the form as a hidden field.

In that way, when you post it back to the server you have track on what Movie and Order this OrderDetail is of, in the action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM