Home > Software engineering >  How to send a List to the other razor page by "HttpContext.Session.Set" in Core 6?
How to send a List to the other razor page by "HttpContext.Session.Set" in Core 6?

Time:01-18

I have saved some rows of data in a list named "viewListNextWeek". I want to send this list to the next razor page, where I'm redirecting to it by

return RedirectToPage("../Food/nextWeekFood");

Based on this, I have tried

HttpContext.Session.Set<List<reserveInfo>>("List", viewListNextWeek);

But I got the error

Error   CS0308  The non-generic method 'ISession.Set(string, byte[])' cannot be used with type arguments    

I also read this, but I don't understand very well what to do.

CodePudding user response:

You can create an extension method to save list of data into session. please refer to this simple demo:

public static class TestSession
    {
        //set session
        public static void SetObjectsession(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        //get session
        public static T GetObjectsession<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

Then use this method to set and get session:

HttpContext.Session.SetObjectsession("A", viewListNextWeek);

HttpContext.Session.GetObjectsession<List<reserveInfo>>("A");
  • Related