markzzz
markzzz

Reputation: 47945

How can I get the Server Side ID of a UserControl?

I need to do a __doPostBack in a WebForms of this LinkButton:

<asp:LinkButton ID="AggiungiSocial" runat="server" onclick="cmdAggregaSocial_Click">Link</asp:LinkButton> 

I see that .NET process it as:

javascript:__doPostBack('ctl00$ContentPlaceHolder1$Dashboard1$RepeaterSocials$ctl00$AggiungiSocial','')

so what I need is javascript:__doPostBack('ctl00$ContentPlaceHolder1$Dashboard1$RepeaterSocials$ctl00$AggiungiSocial','').

But rendered, the ID is instead ContentPlaceHolder1_Dashboard1_RepeaterSocials_AggiungiSocial_0

So Do I need to do a javascript replace/parse of that ID or is there a method to get this "__dopostback" UserControl id?

Such as:

var ServerIDUserControl = link.attr('href').replace("javascript:__doPostBack(", "").replace("','')", "");

(which is terrible imo).

Upvotes: 0

Views: 380

Answers (2)

Grant Thomas
Grant Thomas

Reputation: 45083

(Perhaps depending on which (ASP).NET version you're using) the name attribute value will contain the string you're looking for, as opposed to the id being made identifier-friendly. An example from a 3.5 site here at work looks like this for a Button:

<input type="submit" 
  name="ctl00$cph_main$ctl00$PerformSearch"
  id="ctl00_cph_main_ctl00_PerformSearch">

I parenthesise the first part simply because I have to admit my ignorance as to when/why this happened - I recall a time when this wasn't the case, and it could be either a 3.5+ thing or a configured thing.

Otherwise you could use the inline server-side script syntax to output the control.UniqueID in the appropriate place.

Upvotes: 1

Ovidiu
Ovidiu

Reputation: 1407

To get the id of the control sent as __EVENTTARGET during postback you need to use the UniqueID property of Control. In your case:

javascript:__doPostBack('<%= AggiungiSocial.UniqueID %>', '');

However, from your example I see that your control is nested inside a repeater called RepeaterSocials. In this case, your code might look like this:

javascript:__doPostBack('<%= RepeaterSocials.Items[0].FindControl("AggiungiSocial").UniqueID %>', '');

But my advice is to not use this approach. You can instead capture the Repeater.ItemCommand event and see which button was clicked inside the repeater.

Upvotes: 0

Related Questions