gpt4 book ai didi

asp.net-mvc-3 - 如何访问保存在 session 中的列表内的对象。 ASP.NET MVC 3

转载 作者:行者123 更新时间:2023-12-02 18:09:09 27 4
gpt4 key购买 nike

所以我有这个代码:

var list = new List<Carrito> { 
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};

Session["list"] = list;

return View();

然后我加载 View ,但我不知道如何打印 session 内的内容。有什么想法吗?

这是我在 View 中使用的代码,但不起作用:

@foreach(var item in (IEnumerable<object>)Session["list"] )
{
<p>@item.ProductId</p>
}

最佳答案

这就像从 session 变量中读回值并将其转换为原始类型一样简单,然后做任何你想做的事情

示例:

@{
if(Session["list"]!= null)
{
var listBackFromSession = (List<Carrito>)Session["list"];
// do what you want
}
}

我的建议是使用更优雅的ViewBag方式。

来自asp.net mvc官方网站关于Viewbag的引用:

New "ViewBag" Property

MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)

此外,这是一篇关于 MVC 中保存数据的不同方法的好文章:http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

示例:

var list = new List<Carrito> { 
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};

// use ViewBag
ViewBag.myList = list;

then inside your view, read them back like this:

var myList = (List<Carrito>)ViewBag.myList;
// your code

关于asp.net-mvc-3 - 如何访问保存在 session 中的列表内的对象。 ASP.NET MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10813870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com