ASP.NET document.getElementById ('<% = Control.ClientID%>'); returns null

I am trying to get a server control in JavaScript. For testing purposes, I call the JavaScript function from the page load event.

 protected void Page_Load(object sender, EventArgs e){ ClientScript.RegisterClientScriptBlock(GetType(), "js", "confirmCallBack();", true); } 

And my JavaScript function

 function confirmCallBack() { var a = document.getElementById('<%= Page.Master.FindControl("PlaceHolderContent").FindControl("Button1").ClientID %>'); var b = document.getElementById('<%=Button1.ClientID%>'); } 

My problem is that both a and b return null. Even when I look at the source of the page, the correct client ID is returned.

I must add that I am using the main page.

Any ideas.

+4
source share
2 answers

Gotcha!

You should use RegisterStartupScript instead of RegisterClientScriptBlock

Here is my example.

MasterPage:

 <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="prueba.MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function confirmCallBack() { var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>'); alert(a.value); } </script> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> 

WebForm1.aspx

 <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:Button ID="Button1" runat="server" Text="Button" /> </asp:Content> 

WebForm1.aspx.cs

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace prueba { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true); } } } 
+8
source

Is Button1 visible? I mean, from the server. Verify that Button1.Visible is true.

Controls that are not Visible will not be displayed in HTML, therefore, although they are assigned ClientID , they do not actually exist on the client side.

0
source

Source: https://habr.com/ru/post/1390753/


All Articles