【问题标题】:Calling Javascript function from Code Behind in C#从 C# 中的代码隐藏调用 Javascript 函数
【发布时间】:2015-05-23 04:07:58
【问题描述】:

我在外部 JS 文件中有一个 javascript 函数。我想从后面的代码中调用它。我怎样才能做到这一点 ? 我在某个地方读到了 ScriptManager.RegisterStartupScript 可以做的事情,但是如何,谁能解释我。

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);

 }

【问题讨论】:

标签: javascript c# asp.net


【解决方案1】:

我经常用这个

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

基本上,它只是将该行插入您的页面并在页面加载后立即运行

【讨论】:

  • 将警报定义为您希望在警报中看到的任何变量
  • 我的 Function1() 包含一些大逻辑,我也想重用它们。所以我需要保留在 EXt JS 文件中。
  • Function1() 在后面的代码中吗?从 js-->c# 进行通信有点棘手。如果是这种情况,最简单的方法是使用 js 中的 ajax 函数
  • 您是否尝试将整个函数传递给页面?那行不通
  • 我只是试图调用函数,而不是传递它。
【解决方案2】:

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

//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);            
}

Here 是一个提供更多详细信息和示例的站点

MSDN 也有一个很棒的演练,包含多个示例

This是上面列出的攻略中我最喜欢的,很全面

【讨论】:

  • 可能是因为您尝试在 javascript 处理之前调用它,请注意我的按钮是如何通过单击按钮触发的,而您在预渲染函数中拥有您的
【解决方案3】:

你可以试试

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

或

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

另一种方法是

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

这也适用于部分回发。

【讨论】:

  • @hellotemp11 试试 this.GetType() 而不是这个,GetType()
  • @hellotemp11 也尝试通过放置警报而不是 function1() 位置并检查它是否工作
【解决方案4】:

示例代码,其中将包含 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);
        }
    }
}

【讨论】:

  • “脚本”和“myScript”应该相同吗?你为什么在这里使用这两个变量?
【解决方案5】:

你可以试试这个..

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

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多