Vb6 “Tag” property equivalent in ASP.Net?

后端 未结 8 1333
迷失自我
迷失自我 2021-01-12 11:19

I\'m looking for ideas and opinions here, not a \"real answer\", I guess...

Back in the old VB6 days, there was this property called \"Tag\" in all controls, that wa

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 11:59

    I took mdb's brilliant solution, and ported it over to C# for my own needs. I also changed the Tags from a Dictionary of String, String, to a Dictionary of String, Object... since theoretically any type of object can be stored in the Session, not just strings:

    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    
    public static class Extensions
    {
        public static void SetTag(this Control ctl, object tagValue)
        {
            if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))
                ctl.SessionTagDictionary()[TagName(ctl)] = tagValue;
            else
                ctl.SessionTagDictionary().Add(TagName(ctl), tagValue);
        }
    
        public static object GetTag(this Control ctl)
        {
            if (ctl.SessionTagDictionary().ContainsKey(TagName(ctl)))
                return ctl.SessionTagDictionary()[TagName(ctl)];
            else
                return string.Empty;
        }
    
        private static string TagName(Control ctl)
        {
            return ctl.Page.ClientID + "." + ctl.ClientID;
        }
    
        private static Dictionary SessionTagDictionary(this Control ctl)
        {
            Dictionary SessionTagDictionary;
            if (HttpContext.Current.Session["TagDictionary"] == null)
            {
                SessionTagDictionary = new Dictionary();
                HttpContext.Current.Session["TagDictionary"] = SessionTagDictionary;
            }
            else
                SessionTagDictionary = (Dictionary)HttpContext.Current.Session["TagDictionary"];
            return SessionTagDictionary;
        }
    }
    

提交回复
热议问题