Ali Sohrabi
Ali Sohrabi

Reputation: 125

How to get object attributes from a session

I have a class named "admin" in my asp.net C# project.
It is:

public class Admin
{  
    private int ID;
    private string FirstName, LastName, IsMainAdmin, Email, Username, 
            Password,BirthDate, EntryDate;  

    public int id
    {
        get { return ID; }
        set { ID = value; }
    }

    public string firstname
    {
        get { return FirstName; }
        set { FirstName = value; }
}

    public string lastname
    {
        get { return LastName; }
        set { LastName = value; }
    }
    .  
    .  
    .  

After login a session is created like this:

Admin admin = isAdmin(username, password);
    if (admin != null)
    {
        **Session.Add("maskanAdmin", admin);**
        Response.Redirect("panel.aspx");
    }

In other page i need to get admin's ID from session in code behind section after page request via jquery ajax.
Please notice that my code behind Method is [WebMethod] that is not supporting Session Object.
Can i get it? How?

Upvotes: 4

Views: 9096

Answers (4)

huMpty duMpty
huMpty duMpty

Reputation: 14470

var adminObj = (Admin)Session["maskanAdmin"];    
if(adminObj != null)
{
    var id = adminObj.id;
    var fname = adminObj.firstname;
}

Read more about Read Values from Session State

Update

I am not sure why the question is updated after one hour saying you are using the code in web methods.

However, have a look at Using ASP.NET Session State in a Web Service

Upvotes: 6

Michael Biggs
Michael Biggs

Reputation: 460

var adminObj = Session["maskanAdmin"];
if(adminObj != null)
{
    var admin = (Admin)adminObj;
}

Upvotes: 1

user3099253
user3099253

Reputation: 63

Admin variableName = (Admin)Session["maskanAdmin"];

Upvotes: 1

Josh Darnell
Josh Darnell

Reputation: 11433

You just need to cast it back to an Admin type object when you retrieve it from the Session:

Admin admin = (Admin)Session["maskanAdmin"];

Then you can use the properties of the object as normal:

if(admin.ID == someOtherID)
{
    // do stuff
}

Upvotes: 1

Related Questions