简体   繁体   中英

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?

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

我在c#中实现了一个版本的Facebook BigPipe,我使用HttpContextBase Items集合在请求之间存储每个单独的对象。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM