Temporary holding collection of data

1.1k views Asked by At

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?

3

There are 3 answers

0
Ehsan Sajjad On

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");
1
Jian Huang On

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>;
1
Andy T On

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.