As far as I could understand from the question, you have problems to preserve the information that you are adding from your modal form.
I have prepared a demonstration, which can serve as your starting point. It is programmed with pure JavaScript.
The idea of this demonstration is to show you that you can also retain the data as you add, without going to the server, to be added to the list, so you would not need to run your controller's method AgregarProducto()
. Everything is done at the client level with JavaScript.
In the sample code, the "Add to list" button performs two functions agregarObjetos()
and listarObjetos(id, data)
.
var btnAdd = document.getElementById("btnAdd");
btnAdd.addEventListener("click", function() {
agregarObjetos();
listarObjetos("Objetos", objetos);
});
Function addObjects (): In this function we capture the values entered from the modal form.
function agregarObjetos() {
var objeto, nombre, c1, c2;
nombre = document.getElementById("nombre"); // Se obtiene acceso a la caja de texto «nombre».
c1 = document.getElementById("c1");
c2 = document.getElementById("c2");
// El objeto «objeto» contendrá los datos del formulario.
objeto = {}; // Se inicializa el objeto «objeto».
objeto.nombre = nombre.value; // Se añade el contenido de la caja de texto «nombre» en el atributo «objeto.nombre».
objeto.c1 = c1.value;
objeto.c2 = c2.value;
// Se añade un objeto al array «objetos».
objetos.push(objeto);
}
ListObject function (id, data): This function receives two parameters: the identifier of the div tag that will show the table with the objects that are added and the data array (list of objects) ).
function listarObjetos(id, data) {
var divData, contenido, i; // Declaración de variables.
divData = document.getElementById(id); // Obtienes acceso a la etiqueta div que imprimirá la tabla de datos.
contenido = "<table class=\"table table-bordered\"><thead><tr><th>Nombre</th><th>Característica 1</th><th>Característica 2</th></tr></thead>";
contenido += "<tbody>";
for (i = 0; i < data.length; i++) {
contenido += "<tr><td>" + data[i].nombre + "</td><td>" + data[i].c1 + "</td><td>" + data[i].c2 + "</td></tr>";
}
contenido += "</tbody></table>";
divData.innerHTML = contenido; // La tabla resultante se añade al div.
}
Then, once you have the list of objects on the screen, you can send all the data, with the following code.
var btnGuardar = document.getElementById("btnGuardar");
btnGuardar.addEventListener("click", function() {
enviarServidor({
type: "POST",
url: "http://httpbin.org/post", // Aquí debes añadir la url hacia un método de tu controlador que reciba una lista de objetos. (List<Object>).
data: JSON.stringify(objetos),
contentType: "application/json; charset=utf-8",
callback: function(xhr) {
if (xhr.target.readyState === 4 && xhr.target.status === 200) {
alert("Se envió la lista de objetos al servidor.");
}
}
});
});
The function above, sends to an url, the array of objects in JSON format.
Then, you would need a method in an MVC5 controller that receives a list of objects.
Something like the following:
Model:
public class Objetos
{
public string nombre {get; set;}
public string c1 {get; set;}
public string c2 {get; set;}
}
The names of the attributes must match what is sent from the client with JavaScript.
Method in a Controller:
public JsonResult Guardar(List<Objetos> obj)
{
Console.Write(obj[0].nombre); // Debe contener el valor «Objeto 1».
// Otras operaciones.
return Json("Correcto");
}
I'll give you the complete example so you can review it.
(function() {
var objetos = []; // Contenedor de objetos.
var btnAdd = document.getElementById("btnAdd");
var btnGuardar = document.getElementById("btnGuardar");
btnAdd.addEventListener("click", function() {
agregarObjetos();
listarObjetos("Objetos", objetos);
});
/* Guardar todos los datos. */
btnGuardar.addEventListener("click", function() {
enviarServidor({
type: "POST",
url: "http://httpbin.org/post",
data: JSON.stringify(objetos),
contentType: "application/json; charset=utf-8",
callback: function(xhr) {
if (xhr.target.readyState === 4 && xhr.target.status === 200) {
alert("Se envió la lista de objetos al servidor.");
}
}
});
});
function agregarObjetos() {
var objeto, nombre, c1, c2;
nombre = document.getElementById("nombre");
c1 = document.getElementById("c1");
c2 = document.getElementById("c2");
// El objeto «objeto» contendrá los datos del formulario.
objeto = {};
objeto.nombre = nombre.value;
objeto.c1 = c1.value;
objeto.c2 = c2.value;
// Se añade un objeto al array «objetos».
objetos.push(objeto);
}
function listarObjetos(id, data) {
var divData, contenido, i;
divData = document.getElementById(id);
contenido = "<table class=\"table table-bordered\"><thead><tr><th>Nombre</th><th>Característica 1</th><th>Característica 2</th></tr></thead>";
contenido += "<tbody>";
for (i = 0; i < data.length; i++) {
contenido += "<tr><td>" + data[i].nombre + "</td><td>" + data[i].c1 + "</td><td>" + data[i].c2 + "</td></tr>";
}
contenido += "</tbody></table>";
divData.innerHTML = contenido;
}
// Helper genérico para peticiones AJAX.
function enviarServidor(options) {
var newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
options.async = true;
options.contentType = options.contentType || "application/x-www-form-urlencoded";
newXHR.open(options.type, options.url, options.async || true);
newXHR.setRequestHeader("Content-Type", options.contentType);
newXHR.send((options.type == "POST") ? options.data : null);
newXHR.onreadystatechange = options.callback;
return newXHR;
}
})();
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Demo</h2>
<div class="panel-body" id="Objetos">
</div>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal">Añadir</button>
<button id="btnGuardar" type="button" class="btn btn-primary">
Guardar todos los datos
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Añadir Objetos</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="nombre">Nombre:</label>
<input type="text" class="form-control" id="nombre">
</div>
<div class="form-group">
<label for="c1">Característica 1:</label>
<input type="text" class="form-control" id="c1">
</div>
<div class="form-group">
<label for="c2">Característica 2:</label>
<input type="text" class="form-control" id="c2">
</div>
<button id="btnAdd" type="button" class="btn btn-default" data-dismiss="modal">Añadir a la lista</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
</div>