I’m a little confused on how to use hidden fields for persisting data in my MVC application. (I am also open to using Session if that makes sense.)
Basically, I have an application that asks a series of questions (which can arrive in different orders depending on the answers given by the user). These questions are provided as a partial view from a single controller (which calls a helper method that understands the order of how the questions should be asked). When the user answers the question, the I use Ajax to submit the current answer which, updates the sidebar with their current answers. (They can go back at any time to change an answer to a question.) All the answers to my questions are stored in a single “Answers” model object (with a property for each answer).
Based on my understanding of hidden fields, I have to provide hidden fields in every single view for every single question in order to persist that data. Is this correct?
If this is correct, would it make more sense to use a Session object? I would think it would be inefficient (and very not DRY) to have to update every view with all the model types every single time. It seems people have conflicting opinions on this and I am not educated well enough in persisting data (and not using some data source) to be sure of my decision.
If you end up with a hidden field for every field/question, realize that this will also add to the payload that you’re sending down from (the DOM itself) and sending up to (form variables) the server. While this may not be bad for a few hidden fields, I think it becomes fairly unmanageable and inefficient after a while.
Session may be a good solution here, since you don’t have to duplicate your questions with a hidden field. The downside is that you need to make a network hop (or read from an in-memory cache) each time you send data to the server to rehydrate your session.
Without knowing a lot about your situation, I think I’d lean more towards the session idea.
The other thought I had would be to use a single hidden field, but keep a JSON-serialized version of your model in it and use JavaScript on the client to update it and use Json.NET on the server-side to read it and work with it. Again, that really depends on the size of the data and what you’re doing with it.
I hope this helps. Good luck!
UPDATE
Based on a question in a comment, here’s how you could use JSON to hold and transmit the data…. Note: I’m more of a jQuery person, so I’m using that instead of pure JavaScript to demonstrate.
In JavaScript, you’d have a variable to hold your object:
As questions are answered, you’d add them to the JavaScript object literal:
When you submit the form, assign the object literal to a hidden field in the form before you actually submit…
On the server side, pull the hidden field out of your form variables and use Json.NET (or other Json deserializer) to deserialize the JSON string…
Hope this helps.