简体   繁体   English

在视图中存储对象以在MVC 3中保持状态持久性的最佳方法?

[英]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. 我正在使用ASP.NET MVC 3,我需要在请求之间维护一个C#对象。 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? 是否有一种简单的方法可以将C#对象序列化到视图中,比如在隐藏字段(类似于Web窗体viewstate)中,然后在每个请求中将其取回?

You could use Html.Serialize from the Futures project. 您可以使用Futures项目中的Html.Serialize。 You can get it by Install-Package Mvc3Futures 您可以通过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) . 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. 无论如何,这是做到这一点的一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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