There are several ways to do this inside Controller
. At first you should know, that with every request to controller you are using different instances of the same controller.
First way: to use a singleton. Store value in public static instance, load it once and get the same List every time you ask. However, as it is database values - you have a need to periodically update stored values from database.
public class LoaderSingleton
{
private static readonly LoaderSingleton _instance = new LoaderSingleton();
private List<DataRow> _items;
static LoaderSingleton()
{
}
private LoaderSingleton()
{
}
public static LoaderSingleton Instance
{
get
{
return _instance;
}
}
public List<DataRow> Items
{
get
{
if (this._items == null)
{
this.Load();
}
return this._items;
}
}
public void Load()
{
this._items = //perform load from database
}
}
Second way: to use a Session
variable. Store values in the user session instead of static class. You should not to forget to update values and clean session.
//inside controller
this.Session[str_salesClass] = SalesRepository.SalesCount();
Third way: to use ViewData
variable. Value will be stored only between requests and you should to update it with new values, after last request will be complete.
//inside controller
this.ViewData[str_salesClass] = SalesRepository.SalesCount();
Fourth way: Perform async
requests from your view. For example, you are loading required values to base view, which can asynchronously load another views and when you are sending request for load child view - you should pass loaded data as parameter.
public ActionResult BaseView()
{
ViewBag.Data = SalesRepository.SalesCount();
return View();
}
[ChildActionOnly]
public ActionResult ChildView1(List<DataRow> sales)
{
}
I do not recommend to use Cache
, cause it has unpredictable behaviour. And you will get null
when you are not expected it.