I love clean client IDs - especially with .Net 2.0!
ASP.Net 4.0 got a brand spanking new feature. Clean ClientID’s! ABOUT BLOODY TIME… Only, I’m working on a legacy application which can’t be migrated to 4.0 :(
So why do we need Nice Readable, predictable ClientID’s? I can think of two main reasons, outside of that, I would assume you’re doing it wrong.
What do I mean by spaghetti code? I mean this stuff:
I absolutely detest seeing this sort of thing. It makes me sick, and worst of all you can’t pull this sort of code back to an external js file. In Web Forms, spaghetti coding is NOT your presentation, your server control is your presentation, the spaghetti code is your binding, and this should be in the codebehind.
Right, so what is my solution? Well I basically find all the server controls that are of a particular type, and write the information as a Json array to the HTML doc.
I’ve put the project on codeplex and named it, Awesome.ClientID, because everything I do is awesome, atleast I like to think so :)
There’s a few issues and the code is a little messy since I rushed it, but it works.
<fieldset> <ul> <li><label>Username: </label> <asp:textbox id="txtUserName" runat="server" /></li> <li><label>Email: </label> <asp:textbox id="txtEmail" runat="server" /></li> </ul> <asp:button id="btnSubmit" runat="server" text="Submit" /> </fieldset>
This would get put into the HTML Doc like so:
I have a property I set in my page with an attribute against it ‘CanSerializeProperty’, this will now get serialized just like the controls:
Originally intended for just .NET 2.0/3.5, the properties feature is pretty handy for .NET 4.0 also.
I’ve got some additional features I’m going to add, at the moment it serializes for every page, but I’m going to add an attribute for pages to turn the feature off. And possibly make a web.config section so you can specify the controls you want to serialize. That way you can easily add controls from libraries such as Telerik without needing to recompile the project.blog comments powered by Disqus