【问题标题】:How to access the gridview control in a usercontrol from a javascript method如何从 javascript 方法访问用户控件中的 gridview 控件
【发布时间】:2017-01-16 14:20:04
【问题描述】:

我正在尝试从 javascript 方法访问用户控件并在该控件中找到 gridview 以检查在 gridview 上选中的复选框的数量。 但是当我尝试从 JS 方法中的 usercontrol 获取 gridviews ID 时,它会显示错误:此名称在当前上下文中不存在。下面是我写的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test.Web.uc"
MasterPageFile="~/SiteMain.Master" EnableEventValidation="false" %>

<%@ Register Src="~/UserControls/UC1.ascx" TagName="uctest" TagPrefix="uc" ID="gv_uc" %>

<script type="text/javascript">
function FindCheckBox()
{
   var checkBoxSelector = document.getElementById('<%=gv_uc.("gvgridname").ClientID%>');
}
</script>

gvgridname 是用户控件上的网格视图。

【问题讨论】:

  • 这个gv_uc.("gvgridname").ClientID 看起来不对,应该是gv_uc.ClientID
  • FindCheckBox() 放入UserControl 或将ClientID 作为变量发送到FindCheckBox()。这样,它将适用于单个页面上的多个控件。
  • @Andrei 即使我尝试写 gv_uc 它说名称在当前上下文中不存在。
  • @VDWWD 所以用户控件的客户端 ID 应该作为参数发送到 FindCheckbox。?
  • 是的,这可能是最简单的:function FindCheckBox(ID) { var checkBoxSelector = document.getElementById(ID); }

标签: javascript asp.net gridview user-controls master-pages


【解决方案1】:

在父页面上,您可以拥有接受来自 UserControl 的 ClientID 变量的 JavaScript 函数。

<script type="text/javascript">
    function FindCheckBox(ID) {
        var checkBoxSelector = document.getElementById(ID);
    }
</script>

然后在 UserControl 中,您可以使用正确的 ID 调用该函数。

<input type="button" onclick="FindCheckBox('<%= GridView1.ClientID %>')" value="ClickMePlease" />

或者在UserControl后面的代码中

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "sendGridID", "FindCheckBox('" + GridView1.ClientID + "')", true);

更新

如果需要父控件的ID,则需要在UC中使用FindControl。

GridView gv = Parent.FindControl("GridView1") as GridView;
Label1.Text = gv.ClientID;

【讨论】:

  • 感谢您的回复,但我需要父页面上的 gridview 的 id 而不是用户控件上的,我需要检查复选框是否在存在于中的 gridview 中被选中用户控制。
  • 更新了我的答案,你可以在 Parent 中找到 GridView 的 ID。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 2010-10-11
  • 2013-11-09
相关资源
最近更新 更多