I store in a list items variable Session
, but when using it in the _layout
, it tells me the following error:
the foreach function cannot work on a variable of type UserOptionIndex because UserOptionIndex does not contain a public instance definition for GetEnumerator
Here is the Model as I define it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PruebaMenu.Models
{
public class OpcionUsuarioIndex
{
public String menu { get; set; }
public String acceso_op { get; set; }
public String opcion { get; set; }
}
}
In the View _layout
:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
@{string codigo_user = Session["ss_UserCodigo"].ToString().Trim().ToUpper();
PruebaMenu.Models.OpcionUsuarioIndex objClass = (PruebaMenu.Models.OpcionUsuarioIndex)Session["class"];
}
@foreach (var item in objClass)
{
}
</script>
The way I fill the list in the Controller is like this:
public ActionResult login_acceso()
{
string opcion_rol = Session["ss_Rol"].ToString();
List<OpcionUsuarioIndex> opcion_permisoUsuario = new List<OpcionUsuarioIndex>();
DataTable dt_opcionpermiso = new DataTable();
String sql_permiso = "SELECT opcion,acceso" + opcion_rol + " FROM permisos";
conexion.conectar();
MySqlDataAdapter datos2 = new MySqlDataAdapter(sql_permiso, conexion.con);
datos2.Fill(dt_opcionpermiso);
List<String> accesos_list = new List<string>();
for (int p = 0; p < dt_opcionpermiso.Rows.Count; p++)
{
opcion_permisoUsuario.Add(new OpcionUsuarioIndex
{
opcion = dt_opcionpermiso.Rows[p][0].ToString(),
acceso_op = dt_opcionpermiso.Rows[p][1].ToString()
});
}
conexion.cerrar();
Session["class"] = opcion_permisoUsuario;
return View();
}
Inside the foreach
, in objClass
it gives me the error:
I would like to know how I can solve this problem, my goal is to be able to loop through a list that is stored in a variable session
in the _Layout
. Thanks in advance.
If your variable
Session["class"]
contains a list of typeList<OpcionUsuarioIndex>
, you must retrieve it in the View in the same way:The code would be the following: