如何在foreach-MVC5视图中使用Session变量对象 [英] How to use Session variable object in foreach-MVC5 View
本文介绍了如何在foreach-MVC5视图中使用Session变量对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究动态菜单.通过传递整个对象来使用会话变量.从控制器可以看出:
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 类型的变量进行操作,因为 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视图中使用Session变量对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文