How to Call javascript function from asp.net code

2020-07-25 09:29发布

问题:

How to call JavaScript function from ASP.NET code behind?

I have JavaScript function and I am using it in a listview with a parameter

I want to use it with another parameter in code behind ?

 <a href="ChatBox.aspx?id=<%# Eval("USR_UserID")%> " 
     onclick="openWindow(this.href,'chat<%# Eval("USR_UserID")%>',600,600);
     this.blur();
     return false;"><%# Eval("USR_UserName") %></a>

that is the listview side. How can I use openwindow function in code behind fore specific ID?

回答1:

I would think using RegisterClientScriptBlock would be the best solution.

Lets say you have a javascript function, MyJSFunction():

function MyJSFunction() {
        ...
}

In your event, such as a Button Click, you would inject the following code:

C#:

ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "MyJSFunction();", true);

VB.NET:

ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "MyJSFunction", "MyJSFunction();", True)

This effectively inserts a call to your JavaScript from the code-behind.



回答2:

Use RegisterStartupScript or RegisterClientScriptBlock

Injecting Client-Side Script from an ASP.NET Server Control http://msdn.microsoft.com/en-us/library/aa478975.aspx