I use OutputCacheAttribute
to cache whole page. Everything works fine unless user makes some changes on the page (for example checks some checkbox or selects some item on dropdown) and leaves the page. Then when he brings back to this page he does not see the changes he made on previous visit (checked checkbox or selected item on dropdown) as it is loaded from the cache the very first html-markup of the page. Is there a way to cache such kind of information?
You would need to use localStorage
. OutputCache
is server-side, and things like checking a checkbox, etc. only exist client-side, unless the user actually posts that back to the server. Even if they did, OutputCache
should vary on param, so the user's post wouldn't (and shouldn't) be cached.
Anyways, you would basically just bind to the change/click events of these form elements and then set their values in localStorage
. For example:
$('#MyCheckBox').on('click', function () {
localStorage.setItem('MyCheckBox', $(this).is(':checked'));
});
Then, on page load, you can retrieve this from localStorage
and reset the values:
$(document).ready(function () {
if (localStorage.getItem('MyCheckBox')) {
$('#MyCheckBox').attr('checked', localStorage.getItem('MyCheckBox'));
}
});
There's pretty broad browser support for localStorage
, but it's still possible that a particular user's browser may not support it. Also, localStorage
requires permission from the user, and can therefore be denied. MDN has a helpful function to check whether you can use it or not:
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
}
Also, handling this field by field, is probably less than ideal. You'd probably be better off looking for a way to abstract the getting/setting logic so you can use it for multiple inputs and types there of. It also may be worth looking into a third-party library like jQuery Phoenix, Garlic or Sisyphus, that can handle this stuff for you automatically.