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

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

I'm trying to retrieve a server control in JavaScript. For testing purposes I am calling 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 is

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 view the page source the correct ClientID is returned.

I should add that I'm using master page.

Any ideas.

回答1:

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here 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);          }     } }


回答2:

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!