How to pass objects, not values, between pages in ASP.net c#?
At开发者_如何学Go the moment I pass values from one page to another. I need to pass objects between pages, how can I do this.
Any help is appreciated.
save object in Session or Cache and then redirect to other page? lets say you have a.aspx in a.aspx you add item to Session.
Session["Item"] = myObjectInstance;
in b.aspx you will get object;
var myObjectInstance = (MyObjectInstance) Session["Item"];
but you should check if anyvalue is set in Session before using it.
you could serialize the object into an input
field in HTML and submit it via form
. Then deserialize it back to the object on the page the form submits to with 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;
}
}
Just don't forget to HTML encode the data, when you pass it via URL.
You can serialize an object in ASP very easily, here are 3 approaches suited for different types of requirements:
1- Using Session to pass objects on 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- To save on your Asp project solution itself:
//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- To save on client machine................
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.
Serializing multiple objects into list elements in as xml file and deserializing them
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();
}
}
In Button Click or Serializing point..
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;
In Button Click or DeSerializing point..
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);
The general approach is to put these values into the Session. However, a rule of thumb for session variables is that they should be kept to a minimum.
What we do is keep the state in a 'stateserver'. This is merely a table in the database that stores values by user.
This table has an xml column which contains the objects from our state which are xmlserialized. The downside is that you are dependent on the xmlserializer and it's limitations. Plus performance wise... on each request you need to perform a query, deserialize the state, process the request, serialize the state again and update the changes back to the database. This is not very optimal when you have a high traffic website.
If hardware is not a problem, a better alternative is to use a real stateserver and just use the session.
精彩评论