1. Create models/product. CS
Public class product
{
Public string name {Get; set ;}
Public decimal price {Get; set ;}
}
2. Create models/productservice. CS
Public class productservice
{
Public list <product> getproducts ()
{
List <product> result = builder <product>
. Createlistofsize (100)
. Build ()
. Tolist ();
Return result;
}
}
3. models/cachewrapper. CS
Public class cachewrapper
{
Public void putproducts (list <product> products)
{
Dictionary <string, Object> itemstocache = new dictionary <string, Object> ();
Foreach (product in products)
{
Itemstocache. Add (product. Name, product );
}
Addcacheitems (itemstocache );
}
Public list <product> getproducts (string [] productnames)
{
List <product> Results = new list <product> ();
List <Object> cacheitems = getcacheitems (productnames );
Foreach (Object cacheitem in cacheitems)
{
Results. Add (cacheitem as product );
}
Return results. orderby (P => P. Name). tolist ();
}
Private list <Object> getcacheitems (string [] keys)
{
Idictionaryenumerator thecache = httpcontext. Current. cache. getenumerator ();
List <Object> Results = new list <Object> ();
While (thecache. movenext ())
{
If (Keys. Contains (thecache. Key ))
Results. Add (thecache. value );
}
Return results;
}
Private object getcachitem (string key)
{
If (httpcontext. Current. cache [Key]! = NULL)
Return httpcontext. Current. cache [Key];
Return NULL;
}
Private void addcacheitems (Dictionary <string, Object> items)
{
Foreach (keyvaluepair <string, Object> item in items)
{
Addcacheitem (item. Key, item. value );
}
}
Private void addcacheitem (string key, object item)
{
Httpcontext. Current. cache. Add (Key, item, null, // Dependencies
Datetime. maxvalue, // absolute expiration
New timespan (0, 0, 2, 0), // sliding expiration
Cacheitempriority. Default, // priority
Null); // callback
}
}
4. Global. asax
Protected void application_start ()
{
Arearegistration. registerallareas ();
Registerroutes (routetable. routes );
Preloadproductcatalog ();
}
Private void preloadproductcatalog ()
{
List <product> Products = new productservice (). getproducts ();
New cachewrapper (). putproducts (products );
}
5. controllers/homecontroller. CS
Public actionresult cachedproducts ()
{
List <product> Products = new cachewrapper (). getproducts (new [] {"name1", "name5", "name98", "name39", "name88", "name34 "});
Return view (products );
}
6. Add a strong type view of cachedproducts, and the View content is list
OK