I am newish to MVC and understand all the great things about it, including the reasons why viewstate isn't available, however there are some circumstances where I think having some kind of view state will be quite handy, In my case I am thinking about list pages with various search filters that can be applied to the list.
Would it be worthwhile implementing some kind of pseudo viewstate to hold this info in some cases? or is there a better solution?
Any examples out there?
Your comments appreciated.
In ASP.NET MVC, state-retention is typically handled by round-tripping the state information back to the view.
For example, in the NerdDinner CRUD examples, they show how you can submit a form, check for errors, and if there are errors, display the form again with the data still intact, including the necessary error messages.
This works because the controller method handling the POST simply passes the data back to the view:
The theoretical answer
ViewState is one of the concepts of ASP.NET WebForms which is considered VERY harmful. It is used to store the state of some controls and renders a very-VERY ugly hidden field into the HTML.
This is undesirable for some people for SEO (search engine optimization) and other reasons.
MVC doesn't provide some of the abstractions that WebForms does, for some very basic reasons:
In truth, HTTP is a stateless protocol, which WebForms try to hide from you by introducing the concept of Controls, and their state and events.
MVC doesn't lie to you and doesn't try to hide anything from you.
The practical anwser
You can use
ViewData
instead ofViewState
.You set an item (
ViewData["Something"] = yourObject
) in theController
, and then you can retrieve it in theView
. You can use it to "remember" whatever you want it to.So, basically, persisting the information consists of reading it from
Request.QueryString
orRequest.Form
in the appropriateController
action, setting it into theViewData
, and then retrieving theViewData
information in theView
.For example:
Controller action:
View:
More stuff
Read some MVC-related questions here (such as this one), and read the MVC book (at least the free NerdDinner chapter).
MVC will be much more understandable for you then, I promise!