views:

127

answers:

2

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 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?
A: 

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?

James L
+1  A: 

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.

Paul