Cust_1
Cust_1

Reputation: 103

How to store list object in session variable using asp.net core. And how to fetch values from session variable from the View?

Using asp.net core how to create a session variable to store the list kind of objects and how to retrieve the values from the view

was trying

HttpContext.Session.SetString("Test", listObject);

.

Upvotes: 6

Views: 13875

Answers (2)

SAID elkharmoudi
SAID elkharmoudi

Reputation: 1

Try IHttpContextAccessor insted of HttpContext to get the current section keys.

The code:

public class UserRepository : IUserRepository
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserRepository(IHttpContextAccessor httpContextAccessor) =>
        _httpContextAccessor = httpContextAccessor;

    public void LogCurrentUser()
    {
        var username = _httpContextAccessor.HttpContext.User.Identity.Name;

        // ...
    }
}

Upvotes: 0

Tomato32
Tomato32

Reputation: 2245

First, you need to add more config at Startup class.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDistributedMemoryCache();                      

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.IsEssential = true;
        });           

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc(routes =>
    {
        // Default Route
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

//Add the following extension methods to set and get serializable objects:

public static class SessionExtensions
    {
        public static T GetComplexData<T>(this ISession session, string key)
        {
            var data = session.GetString(key);
            if (data == null)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(data);
        }

        public static void SetComplexData(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }
    }

public IActionResult Index()
        {
            List<BookingModel> data = new List<BookingModel>();

            for (int i = 1; i < 10; i++)
            {                
                BookingModel obj = new BookingModel
                {
                    BookingId = i,
                    BookingRefNo = $"00{i}",
                    FullName = $"A{i}",
                    MobileNo = $"(00)-{i}",
                    Email = $"abc{i}@gmail.com"
                };
                data.Add(obj);
            }

            HttpContext.Session.SetComplexData("loggerUser", data);
            return View();
        }

public IActionResult Privacy()
        {
            List<BookingModel> data = HttpContext.Session.GetComplexData<List<BookingModel>>("loggerUser");
            return View();
        }

And you can visit this link to refer more: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#session-state

Hope to help, my friend :))

Upvotes: 11

Related Questions