如何在foreach-MVC5 View中使用Session变量对象

时间:2015-04-20 10:30:07

标签: asp.net-mvc razor asp.net-mvc-5

我正在研究动态菜单。通过传递整个对象来使用会话变量。从控制器可以看出:

Session["PackageSbMenu2"] = QueryHelper.Get_Menu("Manage Services", 3).ToList();

在视图中:

@foreach(var t in (Session["PackageSbMenu2"]))
{ 
    <li><a href=@Html.ActionLink(t.Controller, t.Action)>t.Name</a></li>
}

QueryHelper功能负责获取数据:

public static List<MenusDM> Get_Menu(string name, int ParentMenuId)
{
    AutosLoanDbContext context = new AutosLoanDbContext();
    var menues = from parent in context.MenuInRole
     join child in context.Menu on parent.MenuId equals child.MenuId
     where child.Name == name && child.ParentMenuId == ParentMenuId
                 select child;
    return menues.ToList();
}

我得到的错误是:

  

foreach语句不能对类型对象的变量进行操作,因为对象不包含GetEnumerator的公共定义

1 个答案:

答案 0 :(得分:3)

您需要转换Session对象

 @{    
    var menu = Session["PackageSbMenu2"] as List<MenusDM>;
    if(menu != null)
    {
        foreach(var t in menu)
        { 
         <li><a href=@Html.ActionLink(t.Controller, t.Action)>t.Name</a></li>
        }
    }
}