asp.net - Save control's (ASP Panel and children) state in cache -
i'm looking easy , expandable way cache filter settings users. initial thought override save / load viewstate processes panel enclosing filter controls , save / load control state there. have not been able find way though.
is possible without altering state process of entire control, page, or site?
this seemed interesting case, i've taken shot @ solution accomplish functionality. i've come code below, should serve start. works "defaultproperty" of control, adding checks specific control types, cache , set property like.
additionally, sets control cached value on first load of page. not sure if want value of control change between postbacks reflect if user/session had made change.
using system.collections.generic; using system.componentmodel; using system.web; using system.web.ui; using system.web.ui.webcontrols; public class cachedstatepanel : panel { private static dictionary<string, object> cachedfilters { { if (httpcontext.current.cache["cachedfilters"] == null) { httpcontext.current.cache["cachedfilters"] = new dictionary<string, object>(); } return (dictionary<string, object>)httpcontext.current.cache["cachedfilters"]; } } protected override void createchildcontrols() { base.createchildcontrols(); if (!page.ispostback) { foreach (control child in controls) { setfromcacherecursive(child); } } } protected override object saveviewstate() { var state = base.saveviewstate(); if (page.ispostback) { foreach (control child in controls) { loadcachedstaterecursive(child); } } return state; } private static void loadcachedstaterecursive(control current) { if ((current == null) || (current.id == null)) return; var attribs = current.gettype().getcustomattributes(typeof(defaultpropertyattribute), true); if ((attribs != null) && (attribs.length > 0)) { var propname = ((defaultpropertyattribute)attribs[0]).name; var prop = current.gettype().getproperty(propname); if (prop != null) { cachedfilters[current.id] = prop.getvalue(current, null); } } if (current.hascontrols()) { foreach (control child in current.controls) { loadcachedstaterecursive(child); } } } private static void setfromcacherecursive(control current) { if ((current == null) || (current.id == null) || (!cachedfilters.containskey(current.id))) return; var attribs = current.gettype().getcustomattributes(typeof(defaultpropertyattribute), true); if ((attribs != null) && (attribs.length > 0)) { var propname = ((defaultpropertyattribute)attribs[0]).name; var prop = current.gettype().getproperty(propname); if (prop != null) { prop.setvalue(current, cachedfilters[current.id], null); } } if (current.hascontrols()) { foreach (control child in current.controls) { setfromcacherecursive(child); } } } }
Comments
Post a Comment