How to store data from static WebMethods in ViewState

Now I have done some research. I need to save some data that I received from ajax call to my WebMethod on my page, to some place where I can return it back at any time.

At first I thought that ViewState would be a better option. Unfortunately, you cannot refer to it in the same way as to non-static methods. Even if I create an instance of the page to be stored in the ViewState, I believe that at the end of the method, all the data that will be destroyed will be destroyed.

I need this data for the purposes of database calls that I execute in other WebMethods.

The main method in my C # codebehind for my aspx page is as follows:

[WebMethod] [ScriptMethod] public static string populateModels(string[] makeIds) { } 

So, for example, I need to save the selected commands in order to pull them out for future database queries. Since most of my mailboxes are cascaded in terms of filtering and pulling from the database.

Update:

This code works to retrieve and store data in a SessionState in static WebMethods.

  [WebMethod(EnableSession = true)] [ScriptMethod] public static string populateYears(string[] modelIds) { HttpContext.Current.Session["SelectedModels"] = modelIds; string[] makeids = (string[])HttpContext.Current.Session["SelectedMakes"]; } 
+4
source share
2 answers

As Joe Enos pointed out, ViewState is part of the page instance, but you can use the Session cache, for example:

 [WebMethod(EnableSession = true)] [ScriptMethod] public static string populateModels(string[] makeIds) { // Check if value is in Session if(HttpContext.Current.Session["SuperSecret"] != null) { // Getting the value out of Session var superSecretValue = HttpContext.Current.Session["SuperSecret"].ToString(); } // Storing the value in Session HttpContext.Current.Session["SuperSecret"] = mySuperSecretValue; } 

Note. It will also allow you to use part of your page using the ASP.NET AJAX Page Method to simply retrieve or store some values ​​on the server, as well as allow your page backlinks to access data through Session as well.

+6
source

ViewState is a property of the page that goes through the life cycle of an ASP.NET WebForms page. Using WebMethods with AJAX skips the whole page life cycle and generally skips ViewState.

Therefore, you cannot use ViewState the way you look. To use AJAX and still have access to all WebForms materials, such as ViewState and control properties, you need to use UpdatePanels.

You need to find alternatives - for example, instead of ViewState you can put things in hidden fields, and then use javascript to read and populate these hidden fields. If you do, you can read and write to these fields from the javascript and ASP.NET worlds.

+5
source

Source: https://habr.com/ru/post/1498643/


All Articles