Hanusha Loujith

Hanusha Loujith

  • 1.9k
  • 292
  • 6.2k

Error while accessing session variable stored as a list

Oct 21 2020 7:18 AM
I am using an MVC application. I want to display the menu based on the values taken from the database. That menu values should persist till the user logout. That menu values should be there after each redirection. I was saving the data as an array in the session. But not able to use it in the razor page after splitting it into a list. Below is the code used to store the value in session and trying to access it from view page.
Controller method:
public ActionResult Welcome()
string usrname = Session["UserName"].ToString();
SqlCommand cmd = new SqlCommand("sp_getLeftLink", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", usrname);
SqlDataReader rdr = cmd.ExecuteReader();
string[] Desc=new string[100];
int[] Id = new int[100];
int i = 0;
while (rdr.Read())
Id[i] =Convert.ToInt32(rdr[0]);
Desc[i] = rdr[1].ToString();
Session["Id"] = Id;
Session["LinkDesc"] = Desc;
return View();
return RedirectToAction("Index");
In the view:
<li class="active">
<a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Grid Data</a>
<ul class="collapse list-unstyled" id="homeSubmenu">
                List<int> ids = Session["Id"] != null ? (List<int>)Session["Id"] : null;
                List<string> descs = Session["LinkDesc"] != null ? (List<string>)Session["LinkDesc"] : null;
                if (ids != null)
              for (int i = 0; i < 2; i++)
                       <a href="@Url.Action("Index", "Home1", new { id=ids[i]})"> @descs[i]</a>
 But  I am getting error like "Unable to cast object of type 'System.Int32[]' to type 'System.Collections.Generic.List`1[System.Int32]'."  
[Screen shot attached]  
Can  someone please help me to fix the issue?

Attachment: error.rar

Answers (5)