I have a modal window with a form from which I want to return the data entered to a partial view and list them 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 x super, n products are scanned but the ticket is not printed until you have all the products, I want to do the same thing but not save it in the database until you have n objects on the list.
How to keep the data in the list until you want to save it 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
Controller
public ActionResult AddProduct(Object object) {
Object object = new Object(); object.feature=object.feature; ViewBag.objects = object; return PartialView("_PartialView"); }
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>
It's something like that what I want to do
From what I could understand from the question, you are having trouble preserving the information that you add from your modal form.
I have prepared a demo, which can serve as a starting point. It is programmed with pure JavaScript.
The idea of this demo is to show you that you can also retain the data as you add it, without it traveling to the server, to add to the list, so you no longer need to call your controller method
AgregarProducto()
. Everything is done at the client level with JavaScript.In the sample code, the "Add to List" button executes two functions
agregarObjetos()
andlistarObjetos(id, data)
.AddObjects() function: In this function we capture the values entered from the modal form.
ListarObjetos(id, data) function: 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).
So, once you have the list of objects on the screen, you can send all the data, with the following code.
The above function sends the array of objects in JSON format to a url.
So you would need a method in an MVC5 controller that receives a list of objects.
Something like the following:
Model:
The attribute names must match what is sent from the client with JavaScript.
Method in a Controller:
I leave you the complete example so you can review it.