We cannot use session in a static method. So i will show one way in which this can be done without much hassle.
Just use the below syntax
Using this code we can access the session value in static methods too. Create a website. Add a webform to it. Write the below code in the aspx page.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:label id="lblsessionName" runat="server"></asp:label> </div> </form> </body> </html>We have a label on the page. We will assign a name to it using session in a static method. In the code behind file write the following syntax.
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm1: System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Session["UserName"] = "Niks Sangani"; lblsessionName.Text = AssignSession(); } protected static string AssignSession() { string _users = string.Empty; _users = HttpContext.Current.Session["UserName"].ToString(); return _users; } } }
Comments
Post a Comment