When using viewstate, you can say you love and hate it. One of its features is to save the page status, we can use enableviewstate = "false" directly in the page file to block it, but many times we have to use it, however, the lengthy HTML code generated by the page is a headache. The following describes a viewstate compression mechanism. It is mainly implemented by rewriting pagestatepersister.
1. Develop a viewstatefactory and modify the storage mode based on different configurations.
Using system; using system. collections. generic; using system. web; using system. web. ui; using system. web. caching; namespace common {public Enum viewstatemode {cache, session, page, file, database} public class viewstatefactory {public viewstatefactory () {} public static pagestatepersister createviewstate (viewstatemode, page) {Switch (mode) {Case viewstatemode. cache: return New cachestatepersister (PAGE); Case viewstatemode. session: return New sessionpagestatepersister (PAGE); Case viewstatemode. page: Case viewstatemode. file: Case viewstatemode. database: return New hiddenfieldpagestatepersister (PAGE); default: return New hiddenfieldpagestatepersister (PAGE) ;}}// implement a custom method and store it in the server's cache public class cachestatepersister: pagestatepersister {private cache mcache = httpruntime. cache; Public cachestatepersister (page): Base (PAGE) {} public override void load () {string _ vskey = page. request. form ["_ viewstate_key"]; If (_ vskey = NULL) {base. viewstate = NULL;} else {base. viewstate = mcache [_ vskey] ;}} public override void save () {string _ vskey; _ vskey = "viewstate _" + httpcontext. current. session. sessionid + "_" + Page. request. rawurl + "_" + system. datetime. now. ticks. tostring (); mcache. add (_ vskey, base. viewstate, null, system. datetime. now. addminutes (httpcontext. current. session. timeout), cache. noslidingexpiration, cacheitempriority. default, null); this. page. registerhiddenfield ("_ viewstate_key", _ vskey );}}}
2. Add
<add key="ViewStateMode" value="Cache"/>
3. overwrite the pagestatepersister of the page. Here you can develop a basepage and overwrite it in the base class. All the pages are integrated into this page.
// Rewrite pagestatepersister to compress viewstate protected override pagestatepersister {get {viewstatemode = viewstatemode. page; try {Switch (system. configuration. configurationmanager. appsettings ["viewstatemode"]. tostring (). tolower () {Case "cache": viewstatemode = viewstatemode. cache; break; Case "session": viewstatemode = viewstatemode. session; break; default: viewstatemode = viewstatemode. page; break;} return viewstatefactory. createviewstate (viewstatemode, this. page);} catch (exception ex) {return base. pagestatepersister ;}}}