Best way to save an object in a view to save state in MVC 3?

I am using ASP.NET MVC 3 and I have a C # object that I need to maintain between requests. It supports some server-side status information, which is not very important for this issue. Currently, this object is serialized into a session, and then pulled out for each request.

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

Therefore, obviously, I need to save this object on the page and pass it back with requests. I am wondering how best to do this. The client does not need information in this object, and the data in this object is not confidential data, so I am not trying to prevent visitors from viewing it. I'm just wondering what is the best way to keep this object between requests. Is there an easy way to serialize a C # object in a view, for example, like in a hidden field (similar to viewstate web forms) and then take it back to each request?

+6
source share
3 answers

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

+3
source

I implemented the Facebooks version of BigPipe in C #, and I used the HttpContextBase collection of elements to store each individual object between requests.

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

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

  • thingToStore = new KeyValuePair<string, YourType>("key1", yourObject) .
  • Add to session state.
  • Hide the key in a custom form.
  • Get key when calling feedback / action
  • Get the object through the key.

The key can be unique to anyone, so you can enter the type of resistance of the object based on the key generator that you provide.

This is one way to do this, anyway.

+1
source

Source: https://habr.com/ru/post/908531/


All Articles