Pergunta

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"];
     }
Foi útil?

Solução

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.

Outras dicas

ViewState is a property of the page, which runs through the ASP.NET WebForms page lifecycle. Using WebMethods with AJAX skips the entire page lifecycle, and skips ViewState altogether.

So you won't be able to use ViewState the way you're looking. In order to use AJAX and still have access to all the WebForms stuff like ViewState and control properties, you need to use UpdatePanels.

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top