While within MyLo" /> While within MyLo" /> While within MyLo"/>

Getting ClientID from embedded user control

3.7k Views Asked by At

Within a page I have the following defined:

<%@ Register Src="MyLocationControl.ascx" TagName="MyLocationControl" TagPrefix="uc3" %>

While within MyLocationControl.ascx I have, a textbox field that will hold a collection of hidden values like name, address, state etc.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyLocationControl.ascx.cs" Inherits="MyLocationControl" %>
<asp:TextBox ID="uxMyLocationDescription" runat="server" Rows="4" TextMode="MultiLine" ReadOnly="true" Width="225px"/>
<asp:HiddenField ID="MyLocationIDField" runat="server" Visible="true" ClientIDMode="Static" />

and in the .cs I have

public int LocationID
{
    get { return this.MyLocationIDField.Value == String.Empty ? 0 : Convert.ToInt32(this.MyLocationIDField.Value); }
    set { this.MyLocationIDField.Value = value.ToString(); }
}

I cannot access the clientID to assign a value to it.

document.getElementById('<%=uc3_MyLocationIDField.ClientID %>').value = "My Value";

I can however access the textbox with the following...

document.getElementById('MainContentPlaceHolder_uxReservationControl_uxRentalLocation_uxRentalLocationDescription').value = "Put something here";

Can you please advise what I am missing?

2

There are 2 best solutions below

0
John On BEST ANSWER

Use ClientIDMode="Static", eg

<asp:TextBox ID="txtName" runat="server" ClientIDMode="Static" />

This article explains more https://web.archive.org/web/20211020203215/https://www.4guysfromrolla.com/articles/031710-1.aspx

0
sh1rts On

If you're using ASP.NET 4 or above and you have only one control you want to access, John's solution will work.

If not, you can still get it work. The problem with this: -

document.getElementById('<%=uc3_MyLocationIDField.ClientID %>').value = "My Value";

is that you're trying to access the server-side control - MyLocationIDField - using the generated ClientID for it - uc3_MyLocationIDField. This will not work, also, the generated ID is not guaranteed to be the same each time it's rendered.

The point of using the <%= .. %> syntax is that you are referencing server-side code, so this should work, however -

document.getElementById('<%=MyLocationIDField.ClientID %>').value = "My Value";