在会话中存储和检索列表对象 [英] Storing and retrieving list object in session

查看:122
本文介绍了在会话中存储和检索列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人帮我添加和检索列表数据到MVC核心的会话



Please can anybody help me to add and retrieve list data to a Session in MVC Core

public ActionResult OrderNow(int id)
     {
         if (HttpContext.Session.GetString("AnansiCart") ==null)
         {
             List<Item> cart = new List<Item>();
             cart.Add(new Item(_productResipory.GetByID(id),1));

           <<Need to add "cart to a session">>

         }
         else
         {

         }

         return View("Cart");
     }





我尝试过:





What I have tried:

public ActionResult OrderNow(int id)
{
    if (HttpContext.Session.GetString("AnansiCart") ==null)
    {
        List<Item> cart = new List<Item>();
        cart.Add(new Item(_productResipory.GetByID(id),1));


        HttpContext.Session.SetObjectAsJson("AnansiCart", cart);
    }
    else
    {

    }

    return View("Cart");
}



但不知道如何在我的网页上检索它

推荐答案

ASP.NET Core中的会话状态与以前版本的ASP.NET有很大不同,但使用起来并不复杂:

使用Sessions和HttpContext ASP.NET核心和MVC核心 [ ^ ]

Session state in ASP.NET Core is significantly different to previous versions of ASP.NET, but it's not too complicated to work with:
Using Sessions and HttpContext in ASP.NET Core and MVC Core[^]
// Get the cart from the session; if it doesn't exist, create a new one:
List<Item> cart = HttpContext.Session.GetObjectFromJson<List<Item>>("AnansiCart") ?? new List<Item>();

// Modify the cart:
cart.Add(...);

// Store the modified cart:
HttpContext.Session.SetObjectAsJson("AnansiCart", cart);



注意:与以前版本的ASP.NET不同,不会自动存储对复杂对象的更新。在完成修改后,您需要调用 SetObjectAsJson 扩展方法。



为简单起见,您可能希望声明一个façade来封装会话访问:


NB: Unlike previous versions of ASP.NET, updates to complex objects are not automatically stored. You'll need to call the SetObjectAsJson extension method after you've finished making your modifications.

For simplicity, you might want to declare a façade to encapsulate the session access:

public static class CartExtensions
{
    private const string CartSessionKey = "AnansiCart";
    
    public static List<Item> GetCart(this ISession session)
    {
        return session.GetObjectFromJson<List<Item>>(CartSessionKey) ?? new List<Item>();
    }
    
    public static void SaveCart(this ISession session, List<Item> cart)
    {
        session.SetObjectAsJson(CartSessionKey, cart);
    }
}



这样,密钥只存储一次,避免了错别字的可能性,而且你不必再重复相同的代码:


That way, the key is only stored once, avoiding the possibility of typos, and you don't have to keep repeating the same code:

List<Item> cart = HttpContext.Session.GetCart();

cart.Add(...);

HttpContext.Session.SaveCart(cart);


这篇关于在会话中存储和检索列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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