ChevCast
ChevCast

Reputation: 59244

Best way to store an object in the view for state persistence in MVC 3?

I am using ASP.NET MVC 3 and I have a C# object that I need to maintain between requests. It maintains some server-side state information that is not really important to this question. Currently this object is serialized into session and then pulled out upon each request.

The problem with this approach is that the object is specific to session, but I'd like it to be specific to each request. So opening a second tab in your browser would essentially have its own object, rather than sharing the same object as the first tab because it's the same session.

So obviously I need to store this object on the page and pass it back with requests. I'm wondering what the best way to go about this is. The client does not need the information in this object and the data in this object is not sensitive data so I'm not trying to prevent it from being viewed by visitors. I am simply wondering what the best way to store this object between request is. Is there a simple way to serialize a C# object into a view, say like in a hidden field (similar to web forms viewstate) and then grab it back out on each request?

Upvotes: 6

Views: 1939

Answers (3)

cwharris
cwharris

Reputation: 18125

So, another solution - albeit a workaround - would be to store the object within a key-value pair as part of the session state, and store the key as a hidden field.

  1. thingToStore = new KeyValuePair<string, YourType>("key1", yourObject).
  2. Add to session state.
  3. Hide key in the user's form.
  4. Retrieve key on post-back/action invocation
  5. Retrieve object via key.

The key could be unique per anything, so you could inject the type of object persistence, based on a key-generator you provide.

That's one way of doing it, anyways.

Upvotes: 1

James Hull
James Hull

Reputation: 3689

I implemented a version of Facebooks BigPipe in c# and I used the HttpContextBase Items collection for storing each individual object between requests.

var someCollection = (List<T>)ViewContext.HttpContext.Items["SomeCollection"];    

Upvotes: 1

Ot&#225;vio D&#233;cio
Ot&#225;vio D&#233;cio

Reputation: 74320

You could use Html.Serialize from the Futures project. You can get it by Install-Package Mvc3Futures

Upvotes: 3

Related Questions