Home > DeveloperSection > Forums > How to Caching of Hashtable in MVC?
john rob

Total Post:108

Points:756
Posted on    October-30-2014 12:08 AM

 ASP.NET MVC C#  ASP.NET MVC  Mvc4  Hashtable 
Ratings:


 1 Reply(s)
 1157  View(s)
Rate this:
I have a function, simple function from a public class.

That function creates an Hashtable object with information given from database, the part of his function like this:

try {

       while ( dataReader.Read() )

       {

           Hashtable table1= new Hashtable();

           Hashtable table2= new Hashtable();

 

           table1.Add( dataReader["field1"].ToString(), Localization.English(dataReader["field1"]);

 

           table2.Add( dataReader["field2"].ToString(), Localization.French(dataReader["field2"]);

        }

     }

catch ( Exception e )

{

    Console.WriteLine( e.Message );

}


I want to cache these two Hashtables and use them in other classes. As I know, I cannot use HttpRuntime.Cache even if I used System.Web namespace.


I saw that HttpRuntime.Cache could be used in Model class.


Are there other way to cache these Hashtables ?



Elena Glibart
Elena Glibart

Total Post:32

Points:226
Posted on    October-30-2014 12:12 AM

If you have two projects , like a Models or Entities project and your web project all you need to do is add a reference in the Models project to System.Web. If you did not add a reference to System.Web then you won't have access to HttpRuntime or HttpContect even though there is a namespace for System.Web.

After you do so, you'll have access to:

System.Web.HttpRuntime.Cache

and could use

HttpRuntime.Cache.Insert(

                            CacheKey,

                            CacheValue,

                            null,

                            DateTime.Now.AddMinutes(CacheDuration),

                            Cache.NoSlidingExpiration

                        );

                        Hashtable table1 = HttpRuntime.Cache[CacheKey] as Hashtable;

                        HttpRuntime.Cache.Remove(CacheKey);

You'll also have access to

System.Web.HttpContext.Current.Application

and could use

System.Web.HttpContext.Current.Application.Add("table1",myHashTable);

Hashtable table1 = System.Web.HttpContext.Current.Application["table1"] as Hashtable;


Don't want to miss updates? Please click the below button!

Follow MindStick