开发者

ASP MVC 3: Is there a way to have an object in session expire after the user leaves the view?

I have the following problem. In a view I have in ASP MVC where I need to store the original object that was received by the view and compare it to its modified version (which is the result after modifying the original object in the view).

The problem I have is that since the original object is not bound to the view (because there is no reason and I would have to create many hidden fields for this) then it is lost unless I store it in the Session. However, this can caus开发者_如何学Pythone another problem because if the user leaves the page through the navigation menu instead of saving his changes this object will be left in session until it expires, which I think is not good.


It seems to me that you're trying to reason in a "windows forms" or "web forms" way.

So you need to detect the changes made to your object. The pattern to achieve this is rather simple:

  • Get your object from your datastore (whichever it is) and send it to the view
  • Display the fields to edit your object. Have a single hidden field with the id of the object.
  • Post the data to your action method. Retrieve the original object from the datastore using the id, then update the original object with the new values from your post.
  • Persist your changes to the datastore.

As you see, no need to store anything in session. Other than being useless, it would be bad practice.


Why not store the original object in a database and retrieve it from there when the user posts the updated version?


Why not use a ViewBag? It is alive for only as long as you are on a particular view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜