Question

I have a simple ASP.NET page with a MasterPage. Within the MasterPage, I have two login fields:

<input type="text" runat="server" id="txtUserName"/>
<input type="text" runat="server" id="txtPassword"/>

When the controls are rendered to the page, ASP.NET renders the following:

<input type="text" runat="server" id="ctl00_txtUserName" name="ctl00$txtUserName"/>
<input type="text" runat="server" id="ctl00_txtPassword" name="ctl00$txtPassword"/>

If I understand correctly, the name attribute corresponds to the UniqueID property of a control. However, when I'm debugging Page_Load and attempt to view the UniqueID of these fields, they have different values (ctl0$txtUserName and ctl0$txtPassword respectively)!

Note that this does not seem to be an issue on all pages using this MasterPage. Most of them work correctly and use ctl0$txtUserName and ctl0$txtPassword in both rendering and Page_Load.

Any idea what might cause ASP.NET to render a different UniqueID for a control than it uses in Page_Load?

Was it helpful?

Solution

I'm still not sure what was causing the generated UniqueIDs in the MasterPage to be different in Page_Load than when rendered to the page. However, I was able to get around the issue by storing the UniqueIDs of these fields in hidden fields. I was then able to access the values directly in the Request.Form collection.

In other words, I did this:

In the MasterPage -

<input type="text" runat="server" id="txtUserName"/>
<input type="text" runat="server" id="txtPassword"/>

<input type="hidden" id="txtUserNameUID" value="<%=txtUserName.UniqueID%>"/>
<input type="hidden" id="txtPasswordUID" value="<%=txtPassword.UniqueID%>"/>

During Page_Load of the child page -

string username = Request.Form[Request.Form["txtUserNameUID"]];
string password = Request.Form[Request.Form["txtPasswordUID"]];

Hope this helps anyone else struggling with UniqueID weirdness in ASP.NET!

OTHER TIPS

Weird quirk I just became aware of: any wrapping controls that are runat server must also have IDs. For instance, if you have a panel around the control, i.e. whatever "ctl00" is, it must be assigned an ID. If it is not set, it will be allocated one and this can change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top