UniqueID conversion to ClientID

by timvasil 10/30/2007 4:09:00 PM

OK, so chances are you know the differences between ID, ClientID, and UniqueID when it comes to ASP.NET controls.

So if you're rendering your own control from scratch, what type of HTML do you emit?  Do you render the ID, the ClientID, or the UniqueID?  The answer depends on what you plan on doing with the control.

For controls that don't worry about postback, you're generally fine with just the ClientID:

writer.write("<div id='{0}'>", ClientID);

But what about when you need to communicate the action of a control back to the server and you want to leverage the FindControl method?  Finding a control based on a client ID is going to fail, since FindControl operates based on unique IDs.

The solution for this circumstance:  render both ClientID and UniqueID.  It's convention to use the name attribute when rendering the UniqueID.

writer.write("<div id='{0}' name='{1}'>", ClientID, UniqueID);

Now when you want to track the state of a control and inform the server of it on postback, you can use the unique ID on the client side:

document.forms[0].hiddenField.value = target.name;  // tracks the unique ID

... and use it to get back the control on the server side:

Control control = Page.FindControl(Request.Form["hiddenField"]);

Note that there is an underlying ASP.NET infrastructure that handles events, with methods such as ClientScriptManager.GetCallbackEventReference(), which may also come in handy depending on the situation.  In my case, I rarely use the .NET infrastructure and instead favor the greater control over managing postback events manually.

Tags:

ASP.NET

Search

Calendar

«  June 2013  »
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

View posts in large calendar

Recent comments

Archive