Temporary holding collection of data

Which is the best method to temporary hold and access collection of data between one more controllers?

For example, view1.cshtml contain a grid with the following data items:

--------------------
Name | Address | Age
--------------------
aa   | ad1     | 11
--------------------
bb   | ad2     | 22
-------------------
cc   | ad3     | 33
--------------------

and if a user selected first 2 rows, then the selected row items needs to be displayed in a grid on another another view named view2.cshtml. The user can go back to first view again and if select a new row item , then I want to to append the selected item too to the grid displayed on the second view.

I've tried ViewBag and TempData to temporarily store the data. But unfortunately the data getting cleared on sometimes. Which is the best option to solve this situation?

Answers


Since the information on your grid came from some data source, most likely a database which has a unique identifier, when the user clicks on the rows I would simply redirect the user to the other page and pass along the ids of the selected rows.

On the other controller, you would simply retrieve the data for the ids that were passed in.


One way is to pass your object in the action like this:

return RedirectToAction("ActionName", new { data= items });

The controller action method signature could be something like:

public ActionResult LoginFailed(List<T> items)
{
    ...
}

Another way is to store it in tempdata like this, and its once readable, after once read, it si automatically destroyed:

List<AnyType> items = new List<AnyType>();


TempData["MyList"] = items;

And in other controller action read it like this:

List<AnyType> items = (List<AnyType>)TempData["MyList"];

if you want it to be accessable after reading call this:

TempData.Keep("MyList");

I would use Session to store the collection of data since you need to pass data between one or more controllers.

Save:

List<T> items = new List<T>();
items.Add(T);
...

Session["YourCollection"] = items;

Get:

List<T> items = Session["YourCollection"] as List<T>;

Need Your Help

JComboBox within Dialog

java swing dialog jcombobox

I am trying to display combobox within dialog based on id numbers of employees. When user chooses an ID, the application shows data of this employees.