Anu

Anu

  • 1.4k
  • 301
  • 10.6k

Error while accessing session variable stored as a list

Oct 21 2020 7:18 AM
Hi,
 
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()
{
if(Session["UserName"]!=null)
{
string usrname = Session["UserName"].ToString();
connection();
SqlCommand cmd = new SqlCommand("sp_getLeftLink", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", usrname);
con.Open();
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();
i++;
}
Session["Id"] = Id;
Session["LinkDesc"] = Desc;
con.Close();
return View();
}
else
{
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++)
             { 
                   <li>
                       <a href="@Url.Action("Index", "Home1", new { id=ids[i]})"> @descs[i]</a>
                 </li>
             }
            }
 
 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?
 
Thanks,
Hanusha 

Attachment: error.rar

Answers (5)