【问题标题】:How to pass objects, not values, between pages in ASP.net c#?如何在 ASP.net c# 中的页面之间传递对象而不是值?
【发布时间】:2011-03-08 08:53:13
【问题描述】:

目前我将值从一页传递到另一页。我需要在页面之间传递对象,我该怎么做。

感谢任何帮助。

【问题讨论】:

  • 当您说 - 您将值从一页传递到另一页时,我假设您指的是 QueryString...。您可能希望使用 Session 将数据从一页传递到另一页。但是 - 还有其他替代方案(缓存对象/应用程序对象)可以根据要求管理页面之间的数据。
  • 如果我想用 session 来做,你能给我们一些代码吗?

标签: c# asp.net


【解决方案1】:

将对象保存在 Session 或 Cache 中,然后重定向到其他页面? 假设您在将项目添加到会话的 a.aspx 中有 a.aspx。

Session["Item"] = myObjectInstance; 

在 b.aspx 中你会得到对象;

var myObjectInstance = (MyObjectInstance) Session["Item"];

但是你应该在使用之前检查Session中是否设置了任何值。

【讨论】:

    【解决方案2】:

    您可以将对象序列化为 HTML 中的 input 字段并通过 form 提交。然后用Request['paramName']将其反序列化回表单提交到的页面上的对象。

    /// <summary>
    /// Serialize an object
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string Serialize<T>(T data)
    {
        string functionReturnValue = string.Empty;
    
        using (var memoryStream = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memoryStream, data);
    
            memoryStream.Seek(0, SeekOrigin.Begin);
    
            var reader = new StreamReader(memoryStream);
            functionReturnValue = reader.ReadToEnd();
        }
    
        return functionReturnValue;
    }
    
    /// <summary>
    /// Deserialize object
    /// </summary>
    /// <param name="xml"></param>
    /// <returns>Object<T></returns>
    public static T Deserialize<T>(string xml)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            var serializer = new DataContractSerializer(typeof(T));
            T theObject = (T)serializer.ReadObject(stream);
            return theObject;
        }
    }
    

    当您通过 URL 传递数据时,不要忘记对数据进行 HTML 编码。

    【讨论】:

      【解决方案3】:

      您可以很容易地在 ASP 中序列化一个对象,这里有 3 种方法适合不同类型的需求:

      1- 使用 Session 在 Asp 上传递对象:

      //In A.aspx
      //Serialize.
      Object obj = MyObject;
      Session["Passing Object"] = obj;
      
      //In B.aspx
      //DeSerialize.
      MyObject obj1 = (MyObject)Session["Passing Object"];
      
      Returntype of the method xyx = obj.Method;//Using the deserialized data.
      

      2- 节省您的 Asp 项目解决方案本身:

      //Create a folder in your asp project solution with name "MyFile.bin"
      //In A.aspx
      //Serialize.
      IFormatter formatterSerialize = new BinaryFormatter();
      Stream streamSerialize = new FileStream(Server.MapPath("MyFile.bin/MyFiles.xml"), FileMode.Create, FileAccess.Write, FileShare.None);
      formatterSerialize.Serialize(streamSerialize, MyObject);
      streamSerialize.Close();
      
      //In B.aspx
      //DeSerialize.
      IFormatter formatterDeSerialize = new BinaryFormatter();
      Stream streamDeSerialize = new FileStream(Server.MapPath("MyFile.bin/MyFiles.xml"), FileMode.Open, FileAccess.Read, FileShare.Read);
      MyObject obj = (MyObject)formatterDeSerialize.Deserialize(streamDeSerialize);
      streamDeSerialize.Close();
      
      Returntype of the method xyx = obj.Method;//Using the deserialized data.
      

      3- 保存在客户端机器上......

      String fileName = @"C:\MyFiles.xml";//you can keep any extension like .xyz or .yourname, anything, not an issue.
      //In A.aspx
      //Serialize.
      IFormatter formatterSerialize = new BinaryFormatter();
      Stream streamSerialize = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
      formatterSerialize.Serialize(streamSerialize, MyObject);
      streamSerialize.Close();
      
      //In B.aspx
      //DeSerialize.
      IFormatter formatterDeSerialize = new BinaryFormatter();
      Stream stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
      MyObject obj = (MyObject)formatterDeSerialize.Deserialize(stream1);
      stream1.Close();
      
      Returntype of the method xyx = obj.Method;//Using the deserialized data.
      

      【讨论】:

        【解决方案4】:

        将多个对象序列化为 xml 文件中的列表元素并反序列化它们

        using System.Xml.Serialization;
        
        [XmlRoot("ClassList")]
        [XmlInclude(typeof(ClassElements))] //Adds class containing elentsof list
        public class ClassList
        {
            private String FFolderName;
            private List<ClassElements> ListOfElements;
        
            [XmlArray("ClassListArray")]
            [XmlArrayItem("ClassElementObjects")]
            public List<ClassElements> ListOfElements = new List<ClassElements>();
        
            [XmlElement("Listname")]
            public string Listname { get; set; }
        
            public void InitilizeClassVars() 
            {
        
            }
        
            public ClassList() 
            {
                InitilizeClassVars();
            }
        
            public void AddClassElementObjects aItem)
            {
                ListOfElements.Add(aItem);
            }
        }
        
        [XmlType("ClassElements")]
        public class ClassElements
        {
            private String str1;
            private int iInt;
            private Double dblDouble;
        
            [XmlAttribute("str", DataType = "string")]
            public String str
            {
                get { return str; }
            }
        
            [XmlElement("iInt")]
            public int iInt
            {
                get { return iInt;}
                set { iInt = value; }
            }
        
            [XmlElement("dblDouble")]
            public Double dblDouble
            {
                get { return dblDouble; }
                set { dblDouble = value; }
            }
        
            public void InitilizeClassVars()
            {
        
            }
        
            public ClassElements()
            {
                InitilizeClassVars();
            }
        }
        

        在按钮点击或序列化点..

        ClassList ListOfObjs = new ClassList();
        int Count = 5;
        
        for (int i = 0; i < Count; i++)
        {
            ClassElements NewObj = new ClassElements();
            NewObj.str = "Hi";
            NewObj.iInt = 500;
            NewObj.dblDouble = 5000;
            ListOfObjs.Add(NewObj);
        }
        
        // Serialize 
        String fileName = @"C:\MyFiles.xml";
        
        Type[] elements = { typeof(ClassElements) };
        XmlSerializer serializer = new XmlSerializer(typeof(ClassList), elements);
        FileStream fs = new FileStream(fileName, FileMode.Create);
        serializer.Serialize(fs, ListOfObjs);
        fs.Close();
        ListOfObjs = null;
        

        在按钮点击或反序列化点..

        ClassList ListOfObjs = new ClassList();
        
        String fileName = @"C:\MyFiles.xml";
        
        // Deserialize 
        fs = new FileStream(fileName , FileMode.Open);
        personen = (ListOfObjs)serializer.Deserialize(fs);
        serializer.Serialize(Console.Out, ListOfObjs);
        

        【讨论】:

          【解决方案5】:

          一般的做法是把这些值放到Session中。但是,会话变量的经验法则是它们应该保持在最低限度。

          我们所做的是将状态保存在“状态服务器”中。这只是数据库中存储用户值的表。

          此表有一个 xml 列,其中包含来自我们状态的对象 xmlserialized。缺点是您依赖于 xmlserializer,它是 limitations。再加上性能方面......在每个请求上,您需要执行查询、反序列化状态、处理请求、再次序列化状态并将更改更新回数据库。当您拥有高流量网站时,这不是非常理想的。

          如果硬件不是问题,更好的选择是使用real stateserver 并仅使用会话。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-01-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-15
            • 1970-01-01
            相关资源
            最近更新 更多