Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
My question is, is there a way to pass data from one controller to another, more specifically cache-data, and if yes how ?

I have built a system that can create bookings and save them in a cache so i can display them in my view. Now I have a second Controller for a ViewModel, where i need the cache data transferred to.

What I have tried:

This is my Controller which works fine. I have that memoryCache there but its for that Controller only. I need to get that cache data to another Controller.

namespace sopro.Controllers
{
    public class BookingController : Controller
    {
        private static IMemoryCache _cache;
        private List<Booking> bookingsList;
        private List<Guid> cacheKeys;

        public BookingController(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
            bookingsList = new List<Booking>();
            cacheKeys = Booking.guids;
        }

        public IActionResult Index()
        {
            if (_cache != null)
            {
                foreach (Guid guid in cacheKeys)
                {
                    var cacheKey = guid.ToString();
                    bookingsList.Add(_cache.Get<Booking>(cacheKey));
                }

            }

            ViewData["bookings"] = bookingsList;
            return View();
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Booking newBooking)
        {
            if (ModelState.IsValid)
            {
                var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(100));

                _cache.Set(newBooking.InstanceID.ToString(), newBooking, cacheEntryOptions);

                ViewBag.Success = "Booking was successfully created!"; 
                return View();
            }
            else
            {
                cacheKeys.Remove(newBooking.InstanceID);
                ModelState.AddModelError(string.Empty, "Booking was not created! Please enter correct booking details.");

                return View(newBooking);
                //return Content("Failed to create the product. Please try again");
            }
        }

    }
}
Posted
Updated 20-May-20 5:08am

1 solution

If this is per-user data then use the "Session" object. If the data is global then use the System.Web.Caching.Cache object

Cache Class (System.Web.Caching) | Microsoft Docs[^]
 
Share this answer
 
Comments
Todor Iliev 20-May-20 11:17am    
Thanks, it worked with the Cache object.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900