There are a number of code smells that I will try to fix :)
I can only assume that the "Order" is your object EF? If so, I highly recommend keeping it separate from the submission by creating a submission model for your form and copying the data into it. Your view model should only contain properties that your form will use or manipulate.
I also assume orderRepository.GetOrder () is a data layer call that retrieves an order from a data store?
You also declare potentially unused variables. " var order =
" will be loaded even if your model is invalid and " var success =
" is never used.
TryUpdateModel and UpdateModel are not very reliable for real programming. I'm not quite sure that they should be there at all, if I'm honest. I usually use a more abstract approach, such as the / factory service pattern. This works more, but gives you much more control.
In your case, I would recommend the following template. There's a minimal abstraction, but it still gives you more control than using TryUpdateModel / UpdateModel:
public ActionResult ChangeOrder(OrderViewModel model) { if(ModelState.IsValid) { // Retrieve original order var order = orderRepository.GetOrder(model.OrderId); // Update primitive properties order.Property1 = model.Property1; order.Property2 = model.Property2; order.Property3 = model.Property3; order.Property4 = model.Property4; // Update collections manually order.Collection1 = model.Collection1.Select(x => new Collection1Item { Prop1 = x.Prop1, Prop2 = x.Prop2 }); try { // Save to repository orderRepository.SaveOrder(order); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return View(model); } return RedirectToAction("SuccessAction"); } return View(model); }
Not perfect, but it should serve you a little better ...
I am referring you to this post, which seems to be.
source share