使用javascript ASP.NET获取服务器控件上的子控件

Get child controls on server control using javascript ASP.NET

本文关键字:控件 服务器控件 获取 javascript ASP NET 使用      更新时间:2023-11-22

我创建了一个包含按钮的基本复合服务器控件。

<Custom:Class1 ID="testClass" ClientInstanceName="test1" runat="server"></Custom:Class1>

我希望能够使用javascript访问子控件,例如:

var myButton=testClass.FindControl('btnTest');

有办法这样做吗?

创建一个客户端对象来表示服务器端控件(javascript类)。在客户端对象上放置对子控件的引用集合。然后在服务器端的OnPreRender事件中创建或加载一个脚本来定义客户端对象,同时将引用集合传递给其构造函数。

如何嵌入包含客户端对象定义的javascript文件的示例(将此somwhere放在命名空间声明之上:

[assembly: WebResource("myNS.stuff.clientSideObj.js", "application/x-javascript")]
namespace myNS.stuff
{

如何注册WebResouce(OnPreRender)的示例:

 ClientScriptManager cs = this.Page.ClientScript;// Get a ClientScriptManager reference from the Page class.
 Type csType = this.GetType();// Get the type from this class.
 //Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
 String resourceName1 = "myNS.stuff.clientSideObj.js";
 cs.RegisterClientScriptResource(csType, resourceName1);

创建脚本以声明客户端对象实例(OnPreRender)的示例:

String childControlIDsList= getChildControlList();//I am not writing this one.. just look up javascript arrays.
String uniqueScriptKey = "myKey";
StringBuilder theScript = new StringBuilder();
theScript.AppendLine("var myObj = new clientSideObj(" + childControlIDsList + ");");
theScript.AppendLine("window['myClientControl'] = myObj;") //create a client side reference to your control.
cs.RegisterStartupScript(csType, uniqueScriptKey, theScript.ToString(), true);

我将把客户端对象的定义留给您。。。希望能有所帮助!

这是针对Sharepoint可视化web控件的,但适用相同的通用过程:

http://lemonharpy.wordpress.com/2011/07/20/expose-clientid-to-javascript-in-sharepoint-2010-visual-web-control/

从本质上讲,在页面后面的代码中,您可以获得对页面上ClientId的引用,然后将其公开为javascript变量,您可以在jQuery选择器中预先设置该变量。

我觉得这是一个技巧-但我认为它能完成任务。。。

如果您使用的是.net 4.0,您可以将按钮上的"ClientIDMode"属性设置为Static,然后将ID属性设置为类似ID="myButton"的属性,并使用jquery(如so )访问它

 $("#myButton")

如果你不使用jquery,你可以使用

document.getElementById("myButton")

如果您在表单中多次使用该控件,则可以在按钮id前面加上自定义控件id。请记住,也要将自定义控件ClientIDMode属性设置为static。

<asp:Button ID="<%=Me.Id%>_myButton "  ClientIDMode="Static" runat="server"/>

甚至不完全确定这是一个好的做法,也不确定它是否有效,但你可以尝试一下