2015-05-22 135 views
0

我在外部JS文件中有一个JavaScript函数。我想从后面的co0de中调用它。我怎样才能做到这一点 ? 我从ScriptManager.RegisterStartupScript的地方读到了一些我可以做的地方,但是如何,任何人都可以解释我。从C代码中调用Javascript函数#

JS文件:

Function1() 
    { 
     alert("came"); 
    //Some More logic 
    } 

更新

//Tried this But NOT WORKING 
protected void Page_PreRender(object sender, EventArgs e) 
{ 
     ScriptManager.RegisterStartupScript(this, GetType(), "Function1", "Function1();", true); 
    Page.ClientScript.RegisterStartupScript(GetType(), "Function1", "Function1()", true); 

} 
+2

可能重复【如何调用从C#jQuery函数(http://stackoverflow.com/questions/22216177/how-to-call-j-jQuery-function-from-c-sharp) – IamStalker

回答

1

呼唤我经常用这个

string script = string.Format("alert('{0}');",alert); 
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true); 

基本上,它只是插入该行到您的网页,并尽快运行它在页面加载

+0

将警报定义为你希望看到的变量显示在警报中 – stackoverfloweth

+0

我的Function1()包含一些大逻辑, h我也想重复使用。所以我需要保留在EXt JS文件中。 –

+0

是Function1()在后面的代码中?从js - > c#进行通信有点麻烦。如果是这种情况,最简单的方法是使用js – stackoverfloweth

0

你可以尝试

ClientScript.RegisterStartupScript(GetType(),"CallMyFunction","Function1();",true); 

OR

ClientScript.RegisterStartupScript(this,this.GetType(),"CallMyFunction", 
            "Function1();",true); 

另一种方法是

ScriptManager.RegisterStartupScript(Page, typeof(Page), "somekey", script, true);

这也将在部分回发期间起作用。

+0

请参阅更新代码 –

+0

@ hellotemp11您是否使用过任何更新面板? – Sachu

+0

没有更新面板 –

0

要严格回答你的问题,你正在寻找的东西是这样的:

//Following statement is used to call pre-defined javascript function 
protected void btnServerSide_Click(object sender, EventArgs e) 
{ 
    ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction();", true);    
} 

​​是提供一些更多的细节和例子

MSDN还与多个例子

一个伟大的演练网站

This是我上面列出的演练的最爱,它非常全面

+0

请参阅更新代码 –

+0

可能因为您的试图在它被处理之前调用javascript,注意我的按钮点击是如何触发的,并且你有你的预渲染功能 – Pseudonym

+0

至少该警报应该工作然后 –

-1

你可以试试这个..

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "CallMyFunction", "myFunction()", true); 
+0

请参阅更新代码 –

0

示例代码,其中包括JavaScript文件,然后调用后面从方法的代码。

MyJSFile.js

function Test() { 
    alert("hi"); 
} 

WebForm1.aspx.cs中 -

using System; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 

namespace CodeprojectTest 
{ 
    public partial class WebForm1 : Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      var js = new HtmlGenericControl("script"); 
      js.Attributes["type"] = "text/javascript"; 
      js.Attributes["src"] = "JScript1.js"; 
      Page.Header.Controls.Add(js); 
      Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "Test();", true); 
     } 
    } 
} 
+0

这不起作用。我应该写什么“myScript”? –

+0

“脚本”和“myScript”应该是相同的吗?你为什么在这里使用这两个变量? –

相关问题