Friday, 23 November 2012

Bootstrap icon button and ASP.Net

I've started using Bootstrap (from Twitter) to provide a nice polished look to my web site and also, ultimately to provide some pre-formed layouts which will help with responsiveness on mobile devices. One of the things that I immediately noticed was that, as with many Javascript frameworks, it can be difficult to get it to work nicely with ASP.Net and the postback model but a bit of fighting and I can now manage a few things.
One of the things you notice is that bootstrap is designed to play nicely with certain html elements and css makes them behave. Of course, this can mean that you can't get the server tag functionality to make callbacks.
I wanted to use a button with an icon on it to call a method server side. Normally, I could just use an asp:Button and some css and it will look OK. However, I noticed the syntax for creating icon buttons was like this:

<a class="btn" href="#"><i class="icon-align-left"></i></a>

Which you can immediately see is not going to work well with a button. Try and put something between the start and end tag of a button and you (understandably) get an error. I then tried using an asp:Hyperlink which sounds like it might work but then noticed there are no server event handlers on the hyperlink (although the button draws correctly). I didn't want the usual pain of trying to customised calls to __doPostBack and looked through the forums and found someone suggesting I use asp:HtmlAnchor which sounds like the same thing as asp:Hyperlink but lives under the HtmlControls namespace which hints at the fact it is a server representation of a standard HTML control. MSDN looked like it supported but this caused an error in Intellisense. A bit more trawling and I realised that what I needed to do was the following:

<a id="Button3" runat="server" onserverclick="btnGo_Click" class="btn btn-large btn-primary"><i class="icon-forward icon-white"></i></a>

And this is somehow wired up by asp.net by clever interpretation of the "onserverclick" event attribute so that it wires up correctly. That is how you get a bootstrap style icon button with callback!
Post a Comment