如何在ASP.net c#中的页面之间传递对象而不是值?

时间:2011-03-08 08:53:13

标签: c# asp.net

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

感谢任何帮助。

5 个答案:

答案 0 :(得分:12)

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

Session["Item"] = myObjectInstance; 
b.aspx中的

你会得到对象;

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

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

答案 1 :(得分:4)

您可以将对象序列化为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编码。

答案 2 :(得分:2)

您可以非常容易地在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.

答案 3 :(得分:1)

将多个对象序列化为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);

答案 4 :(得分:0)

一般方法是将这些值放入Session中。但是,会话变量的经验法则是它们应该保持最小。

我们所做的是将州置于“州服务员”中。这只是数据库中用于存储用户值的表。

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

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