asp.net webforms and jquery: How to save/restore jquery state between postbacks?

前端 未结 4 1214
庸人自扰
庸人自扰 2020-12-28 10:55

I am building a asp.net webforms (3.5 sp1) application, using jquery where I can to animate the UI, change its state. It has worked great until I started doing postbacks, wh

4条回答
  •  别那么骄傲
    2020-12-28 11:57

    You have two options:

    • Client side cookie
    • Store UI settings server side via postback or webmethod calls

    The second option will require alot more effort but would allow you to provide 'portable' UI settings that could be applied for a user regardless of client machine. If the settings are 'throw-away', I would go for client side cookies.

    How to work with javascript and cookies:

    http://techpatterns.com/downloads/javascript_cookies.php

    I generally store UI settings server side in a database via postbacks, however if users are changing their UI via jQuery and you want to persist those changes, I would probably go about it something like this:

    • add a script manager to your aspx page
    • set EnablePageMethods="true"
    • create a WebMethod in your codebehind
    • in your jQuery methods that update the UI, add a call to your WebMethod and pass back the UI setting
    • store any settings passed to the WebMethod in the database
    • then when the user visits the page the next time, either fetch the settings and populate as many controls server side as you can, or use the jQuery ready method to make a call to another webmethod that fetches the UI settings from the database, passes them back to jQuery allowing you to populate the controls.

    Here is a decent article on jQuery and WebMethod calls:

    http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

    The problem you will need to be aware of is EventValidation; you will get into trouble if you fetch control values outside of the scope of the page lifecycle and then expect to use those settings on postback. For example, adding values to a dropdownlist via a webmethod will throw an error on postback, unless those values were also added to the dropdownlist when the page was built.

提交回复
热议问题