AllPower
AllPower

Reputation: 195

C# - ASP.NET MVC - Convert a List of object , to a List of string, to use in a Session

I have that typed List:

IEnumerable<Resource> ResourceAuthorizedForLoggedUser= resourceAuthorizer.FindAll();

First a try this, but didn't work:

var authorizations= ResourceAuthorizedForLoggedUser.Select(x => x.Id).ToString();

And I need to put inside that Session:

System.Web.HttpContext.Current.Session["Authorized_List"] = authorizations;

To be able to access this data in the base controller

public class BaseController : Controller
{
   public static List<string> authorizations { get { return Getauthorizations(); } }

   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}

And in the end, I get the following error at Getauthorizations method:

It is not possible to convert an object of type 'System.String' to type 'System.Collections.Generic.List`1 [System.String]'

Any ideas how I can convert that list?

Upvotes: 1

Views: 1782

Answers (1)

Ignacio Gonzalez
Ignacio Gonzalez

Reputation: 99

I would write your code as follows:

  1. First, you get your colletion of type Resource:
 IEnumerable<Resource> ResourceAuthorizedForLoggedUser=
 resourceAuthorizer.FindAll();
  1. Then you save the list of Ids (I assume they are strings)
 List<string> authorizations=
 ResourceAuthorizedForLoggedUser.Select(x=> x.Id).ToList();
  1. Save that in the session variable:
 System.Web.HttpContext.Current.Session["Authorized_List"] =
 authorizations;
  1. Read it back from Session:
public class BaseController : Controller
     {
        public static List<string> authorizations { get { return Getauthorizations(); } }


   private static List<string> Getauthorizations()
   {
      List<string> authorizationsList = (List<string>)System.Web.HttpContext.Current.Session["Authorized_List"];
      return authorizationsList != null && authorizationsList.Any() ? authorizationsList : new List<string>();
   }
}`enter code here`

Upvotes: 2

Related Questions