开发者

Where and which data to save into session on an ASP.NET MVC 2 application?

开发者 https://www.devze.com 2022-12-20 15:29 出处:网络
I am having some trouble saving the state of my current view. Currenly I have several selectlist calling their own Action method on the controller that returns the Index view with the filtered model

I am having some trouble saving the state of my current view.

Currenly I have several selectlist calling their own Action method on the controller that returns the Index view with the filtered model based on the values of the selectlist.

I have also written a little FileResult action that creates a csv file based on the current model. But I am only covering one selectlist right now as I only save the value of selectList1 into the session and access it with Session["SelectListValue1"]

  • What are the best practices in this situation?
  • Should I redo the entire (each开发者_Python百科 action for each SelectList) part?
  • Should I save each SelectLists value into the session and check if it's null?
  • Or should I just save the Lambda Expression into the session and modify it during every call?


Well, generally in MVC we don't directly save to Session, it's not considered a best practice b/c of impact to your app's performance. Generally, it's a best practice to make each request as stateless as possible.

Each form should follow the POST-Request-GET pattern where possible, so you're not going to do what you did in WebForms as a rule (where you keep posting back to the same form/action).

So you should consider what the state is that you're trying to capture represents. THe list of possible values is one thing, drawn possibly from a database and stored as a list or enumerable in the cache perhaps (in some scenarios; could look it up every time in others). The value that's selected probably represents a property on osme other object, though, so you should use that as your means of getting out the selected value.

If it's something that's not a part of a persistent object, then you can either just read the post values each time and set the viewstate again (probably the best practice) or, if you need to persist that value across a redirect, then use the TempData bag (which works much like session; in fact uses session under the hood) but values get garbage collected after one the next request, so you don't have to worry as much about the memory bloat.


It doesn't sounds like you need to be using the session at all. Can't you pass the values of your select lists via the query string or in a form?

0

精彩评论

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