I am trying to store a complex object in Viewstate to avoid calling it everytime on page load. I do understand that it needs to be serialized in order to be saved and retrived from Viewstate which means my class should be marked as [Serializable]
It's a fairly complex entity and basically i wish to avoid marking every class as Serializable as it may effect my other dependencies used for mapping.
Class Article
{
Albums albumList { get; set; }
Authors authorList { get; set; }
...
}
Is it even possible and is there any possible way out to save and retrieve the viewstate Object without Serializing?
It seems to me from your use case that "to avoid calling it everytime on page load" screams for cache. I think if you want it to expire maybe set some dependencies, it might work better than session (we don't know all the details).
Now, you can probably use json.net which can help you serialize your info without changing your objects. Just don't abuse viewstate, it can get nasty really fast if you let it grow. Using either session or cache (if it fits your needs) is something that can scale better in the long run.
If this is a display thing, also take a look at Output cache as maybe you can separate your repeated content in a user control or something.
All being said, I wanted to add a little example of what you actually asked using JSON.net (example stolen from them):
//Doesnt need to be marked as serializable
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
//Use this string to save into view state
string json = JsonConvert.SerializeObject(product);
ViewState["something"]=json;
After that, get the string back from ViewState[something] and deserialize it.
string json = (string)ViewState["something"];
Product m = JsonConvert.DeserializeObject<Product>(json);
Warning, code written without compiling it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With