Introduction
There are lots of times when we access user control in our web application, At the time of using user control, we want to access this User control in JavaScript. Given below is the problem and solution for accessing user control in JavaScript.
Problem
While using user control, we want to access this user control in JavaScript, and we try to get its Client ID. But by using document.getElementById('<% =UserControl.ClientID%>')
, it returns null
value.
Solution
To overcome this problem, we create one function in UserControls code behind like "GetClientID
" - it returns the Clientid
of the control, then we can easily access the same.
Follow the Steps
- Create a Web Application, add a Web User Control by clicking add new Item.
- Write the below code in User Control:
Public Function getClientID() As String
Return Controls.ClientID
End Function
- After that, register this user control in your aspx page by adding the below tag:
<%@ Register Src="~/WebUserControl.ascx" TagName="Test" TagPrefix="uc2" %>
- After that, add JavaScript tag in aspx
head
section.
function FunctionName {
alert(document.getElementById('<%=Uctest.getClientID()%>').value);
}
- It shows the value of control which is used in user control.