Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - Saving in Viewstate Without serializing

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?

like image 760
Sangram Nandkhile Avatar asked Oct 19 '22 21:10

Sangram Nandkhile


1 Answers

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.

like image 108
Ernesto Avatar answered Oct 21 '22 17:10

Ernesto