I usually use STATIC implementation when developing Desktop Application and I just got my head bum开发者_高级运维ped on the wall when I use STATIC in ASP.NET (not a good idea)
I think I saw some feedback here before that you can use INTERFACE for passing values between Classes and Pages without using Session.
Can you guys give a good example on how to implement my question? Thanks
here's my sample code
public interface ISessionManager { SessionStates sesState { get; set; } } public struct SessionStates { public string SessionID; public bool isLoggedIn; public string Username; }
Use Session state objects,
Session["variable_name"] = assign any value in one class and use this session state object in any other class.
For example,
using System.Web.SessionState;
//Store the value in the session state object in one class
Session["sessionid"]=Request.QueryString.Get("session_key").ToString();
//Use the session state object in another class
String sessionid=Session["sessionid"].ToString();
Anyway, I decided to do it in another way and I called it SessionManager. I just want to get out of typing the Session variable name everytime I have to use it and this is to prevent some mistyping the session variable name .. so this I what I came up.
using System; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.SessionState; public class SessionManager : IRequiresSessionState { public SessionManager() { } string _sessionID = string.Empty; public string SessionID { get { if (Get("SessionID") == null) Save("SessionID", string.Empty); return Get("SessionID").ToString(); } set { this._sessionID = value; Save("SessionID", value); } } bool _isLoggedIn = false; public bool isLoggedIn { get { if (Get("isLoggedIn") == null) Save("isLoggedIn", false); return Convert.ToBoolean(Get("isLoggedIn").ToString()); } set { this._isLoggedIn = value; Save("isLoggedIn", value); } } string _username = string.Empty; public string Username { get { if (Get("Username") == null) Save("Username", string.Empty); return Get("Username").ToString(); } set { this._username = value; Save("Username", value); } } int _selectedCID = 0; public int SelectedCID { get { if (Get("SelectedCID") == null) Save("SelectedCID", 0); return Convert.ToInt32(Get("SelectedCID")); } set { this._selectedCID = value; Save("SelectedCID", value); } } string _selectedCIDValPath = string.Empty; public string SelectedCIDValPath { get { if (Get("SelectedCIDValPath") == null) Save("SelectedCIDValPath", 0); return Get("SelectedCIDValPath").ToString(); } set { this._selectedCIDValPath = value; Save("SelectedCIDValPath", value); } } #region methods void Save(string name, object value) { if (HttpContext.Current.Session[name] != null) { HttpContext.Current.Session[name] = value; } else { HttpContext.Current.Session.Add(name, value); } } object Get(string name) { return HttpContext.Current.Session[name]; } #endregion }
精彩评论