public ActionResult Create(Factura modelo, string operacion = null) { if (modelo == null) { modelo = new Factura(); } if (operacion == null) { if (CrearFactura(modelo)) { return RedirectToAction("Index"); } } else if (operacion == "agregar-detalle") { modelo.Detalle.Add(new Detalle()); } else if (operacion.StartsWith("eliminar-detalle-")) { EliminarDetallePorIndice(modelo, operacion); } ViewBag.Productos = productos; return View(modelo); }
private static void EliminarDetallePorIndice(Factura factura, string operacion) { // se asume que en el parametro 'operacion' viene el index del detalle a eliminar. string indexStr = operacion.Replace("eliminar-detalle-", ""); int index = 0; if (int.TryParse(indexStr, out index) && index >= 0 && index < factura.Detalle.Count) { var item = factura.Detalle.ToArray()[index]; factura.Detalle.Remove(item); } }
private bool CrearFactura(Factura factura) { if (ModelState.IsValid) { if (factura.Detalle != null && factura.Detalle.Count > 0) { // este id posiblemente lo asigne tu base de datos. factura.Id = facturas.Count > 0 ? facturas.Max(x => x.Id) + 1 : 1; return true; } else { ModelState.AddModelError("", "No puede guardar facturas sin detalle"); } } return false; }
public ActionResult Create(Factura modelo, string operacion = null) { if (ModelState.IsValid) { if (modelo.Detalle == null || modelo.Detalle.Count == 0) { ModelState.AddModelError("Detalle", "Debe agregar al menos un detalle para la factura"); } else { facturas.Add(modelo); return RedirectToAction("Index"); } } ViewBag.Productos = productos; return View(modelo); }