Session variables in ASP.Net

Asked

Viewed 1,006 times

0

I have an AJAX method that sends me a certain value, when requested, for a session variable (a list of strings in this case).

Session variable

private static List<string> ListData {
  get{return (List<string>) Session["ListDataSession"];}
  set {Session["ListDataSession"]=value;}

}

AJAX method

 $.ajax({
        type: "POST",
        url: "Teste.aspx/UpdateData",
        data: '{name: "' + "newValue"+ '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
        }
    });

Method C#

[System.Web.Services.WebMethod]
public static bool UpdateData(string name)
{
    UpdateData.Add(name);
    return true;
}

How to make this single-session variable in this type of cases where I need to have declared a static variable to manage the information coming via AJAX?

This question arises because opening two tabs where the same variable is used I cannot guarantee data integrity.

1 answer

1

I believe that would work

private List<string> ListData 
{
get {return (List<string>) HttpContext.Current.Session["ListDataSession"];}
set {HttpContext.Current.Session["ListDataSession"]=value;}

}

In its C method#

[System.Web.Services.WebMethod(EnableSession = true)]
public static bool UpdateData(string name)
{
  UpdateData.Add(name);
  return true;
}

I think that OS link answers your question. https://stackoverflow.com/questions/4758575/how-can-i-access-session-in-a-webmethod

It is never good to use static properties in this case, because if two users are accessing the application at the same time they will access the same data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.