从用户控件中的代码隐藏 C# 调用 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7350184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling JavaScript function from codebehind C# in a user control
提问by aleafonso
Currently, I am calling my JavaScript functions using:
目前,我正在使用以下方法调用我的 JavaScript 函数:
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('Hello World');});", true);
It works perfectly! Even using master page and update panel it works as expected.
它完美地工作!即使使用母版页和更新面板,它也能按预期工作。
However, when I try to do the same in a user control that is embedded in a page that is being called with a jQuery thickbox, it does not work!
但是,当我尝试在嵌入在使用 jQuery 厚框调用的页面中的用户控件中执行相同操作时,它不起作用!
Does anyone know how to solve this issue?
有谁知道如何解决这个问题?
回答by aleafonso
This solved the problem:
这解决了这个问题:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('Hello World');});", true);
As it was mentioned by @Joel, there was a problem with the type I was using as a parameter for the function.
正如@Joel 所提到的,我用作函数参数的类型存在问题。
Note: If you're using a thickbox, probably you are not using the master page in the page that contains the user control. Therefore, jQuery needs also to be referenced in that page since the master page is not partaking in the thickbox.
注意:如果您使用的是厚框,可能您没有使用包含用户控件的页面中的母版页。因此,还需要在该页面中引用 jQuery,因为母版页不参与厚框。
回答by Joel Etherton
It looks to me like what you have is incompatible with respect to types. When you include this in an actual page this portion of the code: (this, typeof(Page),...
works because you're dealing with a Page. Once you put it in a UserControl you're no longer dealing with a Page.
在我看来,您拥有的内容与类型不兼容。当您将其包含在实际页面中时,这部分代码:(this, typeof(Page),...
有效,因为您正在处理一个页面。一旦你把它放在一个 UserControl 中,你就不再处理一个页面。
Something you can try is adding a public property to your user control:
您可以尝试将公共属性添加到您的用户控件:
public System.Web.Page ParentForm { get; set; }
In the page that includes the control include this code either in the Page_InitComplete
or Page_Load
event:
在包含控件的页面中,在Page_InitComplete
或Page_Load
事件中包含此代码:
myUserControl.ParentForm = this;
Then you can modify your scriptmanager statement to be:
然后,您可以将 scriptmanager 语句修改为:
ScriptManager.RegisterClientScriptBlock(ParentForm, typeof(Page), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('Hello World');});", true);
回答by Jesse
Have you ensured that your user control is calling databind()? I've experienced a similar issue before.
您是否确保您的用户控件正在调用 databind()?我以前也遇到过类似的问题。