I run into a situation where I needed different CSS Control Adapters for the ASP.NET Menu Control for differnent browsers, in my case a default one and one for the iPhone.
So my first idea was to just put multiple controlAdapters sections into a .browser file, but for whatever reason that did not work (I still think this should work somehow, if you have the answer, let me know). Then I was looking to just change the adapter in my code, but even Scott Guthrie said it’s not possible. Ok, time to call it a day and get a beer (or two).
But who cares if the Corporate Vice President in the Microsoft Developer Division says it’s not possible, lets go at it again. Eventually I found this post. If it is possible to add and remove Adapters at run time, it clearly has to be possible to change them, no? And indeed, it is possible:
protected override void OnPreInit(EventArgs e) { HttpContext.Current.Request.Browser.Adapters["System.Web.UI.WebControls.Menu, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"] = "Supertext.Adapters.iUiMenuAdapter"; base.OnPreInit(e); } protected override void OnUnload(EventArgs e) { base.OnUnload(e); HttpContext.Current.Request.Browser.Adapters["System.Web.UI.WebControls.Menu, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"] = "CSSFriendly.MenuAdapter"; }
Just add the above code to your aspx page and change the key/value pair appropriately. You can iterate through the Adapters list to get a better idea what is in there and how to replace it.
Now, this is not exactly a schoolbook code sample, but it works and it’s just intended to give you kick in the right direction. In that sense, please no of these “this is unmaintainable code” comments. Thanks!
2 Kommentare zu “Change a CSS Control Adapter in Code”
This is great! Exactly what I am looking for. It appears that if you use a master page, however, it won’t use the control adapter on the very first request even if the code is in the init of the master page – each request thereafter works, though. You can, however put it in the BeginRequest of your global.asax and it will be run for every request including the first, like so…
Dim controlType As String = GetType(ImageButton).AssemblyQualifiedName
If Not HttpContext.Current.Request.Browser.Adapters.Contains(controlType) Then
HttpContext.Current.Request.Browser.Adapters.Add(controlType, “MyNamespace.MyImageBtnAdapter”)
End If
In my project, I made it a little more robust allowing me to change the adapters on the fly (both add and remove) from settings in a database.
Thanks!!!
Glad I could help. And thanks for sharing this with us. I never tried it in a Master Page.