Saving multiple objects from MVC view

后端 未结 3 1992
失恋的感觉
失恋的感觉 2020-12-17 05:58

I\'m writing my first MVC3 application which is a simple order tracking application. I would like to edit the order and the details at the same time. When I edit the order t

3条回答
  •  失恋的感觉
    2020-12-17 06:10

    Using MVC it should be rather straight forward as the framework is designed to to turn a form into a model.

    [HttpGet]
    public ActionResult Edit(int id)
    {
        // (you can probably rewrite this using a lambda
        var orderWithLines = from o in db.Orders.Include("OrderLines")
                             select o;
    
        // Use ViewData rather than passing in the object in the View() method.
        ViewData.Model = orderWithLines.FirstOrDefault(x => x.ID = id);
        return View();
    }
    
    [HttpPost]
    public ActionResult Edit(OrderTracker.Models.Order model)
    {
        if (ModelState.IsValid)
        {
            // call the service layer / repository / db to persist the object graph
            _service.Save(model); // this assumes your view models are the same as your domain
        }
    }
    

提交回复
热议问题