user3085540
user3085540

Reputation: 295

How to set session value from class files

I am using the below code to assign a session variable from class file. But i got the error message "Object reference not set to be an instance of object".

  HttpContext.Current.Session.Add("UserSession", "dsafd");

Upvotes: 0

Views: 4490

Answers (1)

makemoney2010
makemoney2010

Reputation: 1242

The right way to achive your goal is (translated in c# with online tools take care to check () or []):

if ((Session("UserSession") == null)) 
   {
     //example with simple string
     Session.Add("UserSession", "thisIsASimpletString");
    //Exmple with an Object NOTE: the constructor new if is required or you may handling in exception like your
    List<string> list = new List<string>();
    Session.Add("UserSession", list);
    } 
    else
    {
     //different case where session exist
     Session("UserSession") = "thisIsASimpletString";
     //case with object 
     List<string> list = new List<string>();
     Session("UserSession") = list;
    }

If this asnser match your goal mark as answer.

In case you talking about a class which set session value you need to pass context to your calss but is not a very good idea.Is better that you return a value from class to the session or persist the object(class) into the session too

in example( but not suggested and assume that you populated you name and surname properties) :

    protected void Page_Load(object sender, EventArgs e)
   {
    MyObject _class = new MyObject(HttpContext.Current);
    _class.SetNameAndSurname();
    Response.Write(Session("UserInfo").ToString);
   }
    private class MyObject
    {
    public void SetNameAndSurname()
    {
        if ((this.Context.Session("UserInfo") == null)) {
        this.Context.Session.Add("UserInfo", this.Surname + "-" + this.Name);
        } else {
        this.Context.Session("UserInfo") = this.Surname + "-" + this.Name;
        }
    }
    private string _Name;
    public string Name 
        {
        get { return _Name; }
        set { _Name = value; }
    }
    private string _Surname;
    public string Surname
        {
    get { return _Surname; }
    set { _Surname = value; }
    }
    private HttpContext _context;
    public HttpContext Context 
        {
        get { return _context; }
        set { _context = value; }
    }
    public MyObject(HttpContext Context)
    {
        this._context = Context;
    }

     public MyObject()
     {
     }
    }

And there's many other way to achieve same goals in example:SameClass with properties,methods:

protected void Load()
{
     MyObject _class = new MyObject;
     _class.surname="Surname";
     _class.name="Name";
     context.Session.add("UserInfo"),_class.name + "-" + _class.surname);
}

All depend from your class,methods,properties and logic.

Upvotes: 2

Related Questions