如何在foreach-MVC5视图中使用会话变量对象 [英] How to use Session variable object in foreach-MVC5 View

查看:153
本文介绍了如何在foreach-MVC5视图中使用会话变量对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理动态菜单.通过传递整个对象来使用会话变量.从控制器可以看到:

I am working on dynamic menus. Using Session Variable by passing whole object. As can be seen from controller:

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语句无法对类型为object的变量进行操作,因为对象不包含GetEnumerator的公共定义

foreach statement cannot operate on variable of type object because object doesn't contain a public definition for GetEnumerator

推荐答案

您需要强制转换Session对象

You need to cast your Session object

 @{    
    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>
        }
    }
}

这篇关于如何在foreach-MVC5视图中使用会话变量对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆