list data in a partial view by passing it from a modal window

1

I have a modal window with a form from which I want to return the data entered in a partial view and put them on the list as they are added I already have the modal window with an Ajax.BeginForm () and I pass the data to the partial view through a ViewBag but the bad thing is that only one is added at a time and what I want is to add more.

Example:

Like when you make a purchase in super x, n products are scanned but the ticket is not printed until all the products are already there, the same thing I want to do but not saved in the database until there are n objects in the list .

How to keep the data in the list until you want to save them without removing the previous ones? Here my code example I hope you can help me:

Main view with modal window

@model Proyecto.Models.Objeto
<div class="row">
     <div class="col-md-12">
          <input type="text" class="form-control" name="Cantidad" >
     </div>
</div>

<div class="panel-body" id="Objetos">
</div>
<div id="myModal" class="modal fade" role="dialog">
@using (Ajax.BeginForm("AgregarObjeto", new AjaxOptions {UpdateTargetId = "Objetos" }))
  {
  <div class="col-md-12">
    <input type="text" class="form-control" name="Carecteristica1"/>
  </div>
  }
</div

Driver

public ActionResult Add Product (Subject object) {

Object object = new Object ();    object.caracteristica = object.caracteristica;    ViewBag.objects = object;    return PartialView ("_Parcial View"); }

Partial View

I have it like this:

<div class="col-md-4">
ViewBag.Objeto.NombreObjeto
</div>
<div class="col-md-4">
ViewBag.Objeto.Caracteristica1
</div>
<div class="col-md-4">
ViewBag.Objeto.Caracteristica2
</div>

That's something I want to do

    
asked by Xique 25.08.2016 в 18:28
source

1 answer

3

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">&times;</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>
    
answered by 26.08.2016 / 09:51
source