Search code examples
c#model-view-controllerviewdatatempdatastate-management

Save variable value while navigation in MVC


I am having one page ABC.cshtml. In the page I have written code for multiple modal popup with "Back" and "Next" buttons. when I click on buttons it navigates from one modal to another.

I am having "Id" which I need to persist when I navigate from one modal to another but "Id" became null.

I have used Tempdata/Viewdata/Viewbag/Hidden field to persist data but no use. I cant use session to save state here. Is there any other way to do this?

Can someone help me to solve this issue?

Thanks in advance.


Solution

  • You could use cache

    Add System.Runtime.Caching

    enter image description here

    //Add cache named Key1. It will expire in 10 minute
    CacheWrapper.Add("Key1", new List<int>(), 10);
    
    //Get the cache
    var result = CacheWrapper.Get<List<int>>("Key1");
    
    //Delete the cache
    CacheWrapper.Delete("Key1");
    

    Create wrapper class like this

    public class CacheWrapper
    {
        private static ObjectCache cache = null;
    
        public static ObjectCache Cache
        {
            get
            {
                if (cache == null)
                {
                    cache = MemoryCache.Default;
                }
                return cache;
            }
        }
    
        public static void Add(string key, object data, double expireInMinute)
        {
            Delete(key);
            Cache.Add(key, data, DateTime.Now.AddMinutes(expireInMinute));
        }
    
        public static object Get(string key)
        {
            if (!Cache.Contains(key))
                return null;
            return Cache[key];
        }
    
        public static void Delete(string key)
        {
            if (Cache.Contains(key))
            {
                Cache.Remove(key);
            }
        }
    }