zoukankan      html  css  js  c++  java
  • C# Web中Session的使用

    1. 关于使用之前要注意的:

      在使用session之前,一定要注意继承自System.Web.UI.Page,或在使用session时加上System.Web.HttpContext.Current:

        如:System.Web.HttpContext.Current.Session["Items"] ="xxx";

    2. 在使用过程中遇到数据类型的转换,具体操作如下:

        将Session中的值转为DataTable类型:

      System.Data.DataTable dtTrendResult = (System.Data.DataTable)System.Web.HttpContext.Current.Session["xxx"];

    3. Web中Session的设置与获取:

    public List<DevicesModel> GetDeviceDataList(string OrderID)
    {
        List<DevicesModel> dms = new List<DevicesModel>();
        if (Session["DeviceList"] == null)
        {
            DevicesModel dm1 = new DevicesModel();
            dm1.ID = 1;
            dm1.OrderID = "ORD0001";
            dm1.DeviceType = "DTM";
            dm1.Manufacturer = "CETE";
            dm1.Model = "MC-202";
            dm1.SerialNumber = "A-3042896";
            dm1.Status = "Order Saved";
            dms.Add(dm1);
    
            DevicesModel dm2 = new DevicesModel();
            dm2.ID = 2;
            dm2.DeviceType = "DTM";
            dm2.Manufacturer = "A&D";
            dm2.Model = "UC-DCC-C";
            dm2.SerialNumber = "B-1221-0012";
            dm2.Status = "Order Saved";
            dms.Add(dm2);
    
            DevicesModel dm3 = new DevicesModel();
            dm3.ID = 3;
            dm3.DeviceType = "ATG";
            dm3.Manufacturer = "A&D";
            dm3.Model = "UA-BBL-C";
            dm3.SerialNumber = "B-1001-0012";
            dm3.Status = "Order Saved";
            dms.Add(dm3);
    
            DevicesModel dm4 = new DevicesModel();
            dm4.ID = 4;
            dm4.OrderID = "ORD0002";
            dm4.DeviceType = "ATG";
            dm4.Manufacturer = "CETE";
            dm4.Model = "MC-232";
            dm4.SerialNumber = "";
            dm4.Status = "Order Saved";
            dms.Add(dm4);
    
            Session["DeviceList"] = dms;
        }
        else
        {
            dms = (List<DevicesModel>)Session["DeviceList"];
        }
        return dms;
    }
    View Code

    4. Session的清空:

    public string ClearSession()
    {
        try
        {
            Session.Remove("DeviceList");
            return "OK";
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }
    View Code

    最后,需要注意的是构造函数中不能使用Session,这应该是所有要注意的了!

  • 相关阅读:
    EOJ二月月赛补题
    cf401d
    cf628d
    cf55d
    HDU 6148 Valley Number
    洛谷 P3413 SAC#1
    洛谷 P4127[AHOI2009]同类分布
    洛谷 P2602 [ZJOI2010]数字计数
    bzoj 3679
    函数和循环闭包的理解
  • 原文地址:https://www.cnblogs.com/sccd/p/5574067.html
Copyright © 2011-2022 走看看