Tengo este ViewModel:
public class ComprasCreateModel
{
public int ClienteId { get; set; }
public int JuegoId { get; set; }
public List<DetalleCompra> DetalleCompra { get; set; }
public ComprasCreateModel()
{
DetalleCompra = new List<DetalleCompra>(); // instanciamos la propiedad para que no sea null y podamos acceder a sus propiedades
}
}
Este Model (tabla en la base de datos):
public class DetalleCompra
{
[Key, Column(Order = 0)]
public int CompraId { get; set; }
[Key, Column(Order = 1)]
public int JuegoId { get; set; }
public virtual Juego Juego { get; set; }
public int Cantidad { get; set; }
[DataType(DataType.Currency)]
public int SubTotal { get; set; }
}
y este controlador:
// POST: Compras/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ComprasCreateModel compra, string submitButton)
{
if (submitButton == "Agregar al Carro de Compras")
{
DetalleCompra detalle = new DetalleCompra
{
Juego = juego,
Cantidad = compra.Cantidad,
SubTotal = juego.Precio * compra.Cantidad
};
compra.DetalleCompra.Add(detalle);
return View(compra);
}
else if (submitButton == "Generar Compra")
{
// acá crearé la compra una vez listado todos los productos en compra.DetalleCompra()
}
}
Y sucede que agrego la primera vez sin problemas un producto a compra.DetalleCompra(), y devuelve la Vista donde se muestra en una tabla el listado de productos y el formulario para seguir buscando y agregando productos.
Pero cuando le doy click nuevamente a "Agregar al Carro de Compras", el modelo "compra" entra al controlador con los datos de ClienteId y JuegoId correctos, pero la lista DetalleCompra entra vacía.
Por lo que siempre tengo un único producto en DetalleCompra.
¿Que sucederá?
Si creen necesario subo la Vista. Pero simplemente lo que hace es poner un formulario para que se le envíe el modelo ComprasCreateModel.
edit:
@model TiendaJuegos.ViewModels.ComprasCreateModel
@{
ViewBag.Title = "Registro";
Layout = "~/Views/Shared/_Layout.cshtml";
TempData.Keep("Clientes");
TempData.Keep("Juegos");
}
<h3>Agregue juegos al Carro de Compras:</h3>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.Label("Cliente", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ClienteId", (SelectList)TempData["Clientes"], new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.Label("Juego", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("JuegoId", (SelectList)TempData["Juegos"], new { @class = "form-control" })
@Html.ValidationMessage("dropError", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Cantidad, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Cantidad, new { htmlAttributes = new { @class = "form-control", @Value = "1", @id = "txtCantidad" } })
@Html.ValidationMessage("cantidadError", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Agregar al Carro de Compras" class="btn btn-default" name="submitButton" />
</div>
</div>
<hr />
@if (Model != null && Model.DetalleCompra != null && Model.DetalleCompra.Count > 0)
{
<div class="form-group">
<table class="table">
<tr>
<th>
Nombre del Juego
</th>
<th>
Cantidad
</th>
<th>
SubTotal
</th>
</tr>
@for (int i = 0; i < Model.DetalleCompra.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Model.DetalleCompra[i].Juego.Nombre)
</td>
<td>
@Html.DisplayFor(modelItem => Model.DetalleCompra[i].Cantidad)
</td>
<td>
@Html.DisplayFor(modelItem => Model.DetalleCompra[i].SubTotal)
</td>
</tr>
}
<tr>
<th>
-
</th>
<th>
-
</th>
<th>
TOTAL A PAGAR: @Html.DisplayFor(modelItem => Model.PrecioTotal)
</th>
</tr>
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Crear Compra" class="btn btn-default" name="submitButton" />
</div>
</div>
}
</div>
}