Calling JavaScript function from codebehind C# in a user control

南楼画角 提交于 2019-12-10 19:04:59

问题


Currently, I am calling my JavaScript functions using:

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!

Does anyone know how to solve this issue?


回答1:


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.

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.




回答2:


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.

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:

myUserControl.ParentForm = this;

Then you can modify your scriptmanager statement to be:

ScriptManager.RegisterClientScriptBlock(ParentForm, typeof(Page), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('Hello World');});", true);



回答3:


Have you ensured that your user control is calling databind()? I've experienced a similar issue before.



来源:https://stackoverflow.com/questions/7350184/calling-javascript-function-from-codebehind-c-sharp-in-a-user-control

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