Persist js user controls state
My RIA application has a lot js UI controls (almost all of their is jQuery UI parts like datepicker, dialog, jqgrid). So then user works with some controls on one page and then go to another page and then clicks back all page components has initial state (textboxes are empty, grids are empty and so on). So how can I persist UI controls state and then restoring it between pages? It seems I need some like JS serialization/deserialization methods storing serialized data in user server session. How can I do it with minimal costs? How do you guys it in your projects? Any thougs, links, posts will be very appreciated. Thank you guys in advance!
P.S. My project is ASP .NET MVC3
EDIT
Just now I remember about memnto desig开发者_如何学编程n pattern. Could anyone of you advice me something related to this idea? Thanks again!
I wrote this as a comment of your question but I'm putting it as an answer as it might be the only way to do this without having to "hack" it with some sort of side plugins.
The use of Viewstate have nothing to do with you using or not JQuery UI "addins". All you have to do is use server-side controls instead.
Note that for this you have to use the control client-side name, something like:
$('#<%= MyDateTextbox.ClientID %>').datepicker();
This way you can apply JQuery UI on server-side controls and take advantage of the Viewstate restoring the controls value on back-button navigation.
I would do it using Persist-JS (Persist-JS on GitHub), jQuery (which you are using already) and json.js (JSON-js on GitHub) . Something like this:
var store;
//Restore form data
$(function() {
store = new Persist.Store('My Page Store');
var formDataStr = store.get('formdata');
if (formDataStr !== null) {
var formData = eval('(' + formDataStr + ')');
if (formData.hasData) {
$(':input').each(function() {
if (this.name != undefined && this.name != "") {
if (formData[this.name] != undefined) {
$(this).val(formData[this.name].value);
}
}
});
}
}
});
and...
//Persist form data
$(window).unload(function() {
var formData = {};
$(':input').each(function() {
if (this.name != undefined && this.name != "") {
formData[this.name] = {};
formData[this.name].value = $(this).val();
}
});
formData.hasData = true;
store.set('formdata', JSON.stringify(formData));
});
In other words, loop through all the inputs on the page, store their value ($.val()
), create a JSON object and persist it for these values. When restoring the form, simply do the opposite -- loop through the inputs and grab the properties off of the JSON object by name formData[name]
. There's some defensive stuff in there (ie: check for persisted object to be null, which is how persist-js works).
精彩评论