Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Data from static WebMethods into the ViewState

Now I have done some research. I need to store some data that I have retrieved from an ajax call to my WebMethod on my page into some place where I can pull it back again anytime.

I thought at first that the ViewState would be the best option. Unfortunately you cannot reference it in the same way you can in non-static methods. Even if I make instance of the page to store it in the ViewState, I believe that it would be de-instantiated at the end of the method destroying whatever data I saved.

I need this data for the purpose of database calls that I am doing in other WebMethods.

The basic method in my C# codebehind for my aspx page looks like this:

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

    }

So for example I need to save the selected makes to pull from for future database calls. Since most of my boxes cascade in terms of filtering and pulling from the database.

Update:

This code works for retrieving and storing data in the 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"];
     }
like image 588
Alexander Ryan Baggett Avatar asked Aug 23 '13 16:08

Alexander Ryan Baggett


1 Answers

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

[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: This will also allow you to use part of your page with ASP.NET AJAX Page Methods to just get or store some values to the server, while also allow your page postbacks to have access to the data via Session as well.

like image 157
Karl Anderson Avatar answered Oct 05 '22 22:10

Karl Anderson