HTML and CSS Reference
In-Depth Information
You can test the application by making some selections and closing the browser window without
saving the data. If you open the survey form again, it should show your earlier selections. You can then
submit the answers and check whether they're saved in the SurveyDb database.
Passing Data as Hidden Form Field
In the Survey application that you just developed, data from the client side is passed to the server using the
jQuery $.ajax() method. This works nicely because you don't submit the entire page to the server.
However, in many cases you may want a full-page postback to the server.
Suppose you've developed the Survey application as a non-Ajax application. Further assume that the
survey is split into three separate web pages like a wizard, such that each page displays a small subset of
the total questions. In this case, data stored in localStorage needs to be sent to the server when the final
wizard page is submitted. The application doesn't use Ajax, so how can you pass web storage data to the
server? A simple way is to use a hidden form field. You can read key-value pairs from web storage, store
them in a hidden field, and then submit the page to the server for further processing.
Assuming the Submit Answers button on the survey form causes a full-page postback, you can handle
its click event and set a hidden form field using the client-side script shown in Listing 7-14.
Listing 7-14. Transferring localStorage Data into a Hidden Field
function OnPostback() {
var data = '';
for (var i = 0; i < storage.length; i++) {
var key = storage.key(i);
var value = storage[key];
var pair = '"' + key + '":"' + value + '"';
data = data + pair + ",";
if (data.charAt(data.length - 1) == ',') {
data = data.substring(0, data.length - 1)
data = '{' + data + '}';
Listing 7-14 essentially generates the same JSON key-value pairs as in the previous case. This time,
however, the JSON data is assigned to a hidden field with ID hiddenAnswers . On the server side, an action
method handles the form postback. One such implementation is shown in Listing 7-15.
Listing 7-15. Handling the Postback on the Server
public ActionResult Index(FormCollection form)
string jsonData = Request.Form["hiddenAnswers"];
Dictionary<string, string> data =
JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
//save data here
return Index();
Search WWH ::

Custom Search