2

I have a session value and a function in a apsx.cs page and I am using jquery webmethod to insert data into database.

Now i want to access session value and function in webmethod but it gives some error.

Below is my Page load code:

int nUserId = Convert.ToInt16(Session["UId"]);

And a Function :

    public int CalcUser()
    {
       return Convert.ToInt16(Session["UId"]) * 2;
    }

Now below is my Webmethod:

    [WebMethod]
    public static void Save()
    {
        UserInfo objUser = new UserInfo();
        objUser.Useid = Convert.ToInt16(Session["UId"]);
        objUser.CalcUser = CalcUser();
        ... Save into Database           
    }

So how can I use session value and function in webmwthod.

Thanks

2 Answers 2

2

You need to explicitly state that you want to use Session with your ASP.NET AJAX Page Method by using the EnableSession= true value in the WebMethod attribute, like this:

[WebMethod(EnableSession = true)]
public static void Save()
{
    UserInfo objUser = new UserInfo();
    objUser.Useid = Convert.ToInt16(HttpContext.Current.Session["UId"]);
    objUser.CalcUser = CalcUser();
    ... Save into Database           
}

Note: You must fully qualify the namespace of the session (HttpContext.Current.Session).


To use the CalcUser() function you need to make it static and fully qualify the Session object, like this:

public static int CalcUser()
{
   return Convert.ToInt16(HttpContext.Current.Session["UId"]) * 2;
}

Note: ASP.NET AJAX Page Methods only have access to static methods, as there is no instance of the page (or any class for that matter).

Sign up to request clarification or add additional context in comments.

3 Comments

Hi For Session it works fine but how can I use CalcUser() function in webmethod.
To use the CalcUser() method you need to make it static, see updated answer.
@Hitesh - glad it is working for you. Feel free to up-vote the answer as well. :-)
0

You need to use [WebMethod(EnableSession = true)] on webmethod
Then you can use like Context.Session["key"]

    [WebMethod]
    [WebMethod(EnableSession = true)]
    public static void Save()
    {
        UserInfo objUser = new UserInfo();
        objUser.Useid = Convert.ToInt16(Context.Session["UId"]);
        objUser.CalcUser = CalcUser();
        ... Save into Database           
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.