简体   繁体   English

从ASPX CodeBehind执行JS代码

[英]Executing JS code from ASPX CodeBehind

I have the following in my .aspx file: 我的.aspx文件中包含以下内容:

<head runat="server">
    <script type="text/javascript" src="js/code.js"></script>
</head>
...
<asp:Button ID="btnSend" runat="server" Text="Submit" OnClick="btnSend_Click" />

And in the code-behind: 并在后面的代码中:

protected void btnSend_Click(object sender, EventArgs e)
{
// Code to add data to database
// Code to execute JavaScript function in code.js telling page transaction is complete
}

Each time I test this, the data is added to the database. 每次测试时,数据都会添加到数据库中。 0 or 1 is returned based on whether the transaction is successful or not. 根据交易是否成功返回01 The code I'm using to call the JavaScript function is: 我用来调用JavaScript函数的代码是:

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "JSScript", "form_success(1);", true);

However the JavaScript itself is not executed. 但是,JavaScript本身未执行。 I've also tried Page.ClientScript.RegisterClientScriptBlock and ClientScript.RegisterStartupScript . 我还尝试了Page.ClientScript.RegisterClientScriptBlockClientScript.RegisterStartupScript

How do I properly execute a JavaScript function from my .JS file correctly? 如何正确地从我的.JS文件正确执行JavaScript函数?

Edit: Actually, I've just found that any function I do that manipulates the HTML on the first page (such as divTest.InnerHtml = "Test"; ) doesn't work either. 编辑:实际上,我刚刚发现我执行的任何操作首页上HTML的函数(例如divTest.InnerHtml = "Test"; )也不起作用。

Edit 2: Oopsie, found the problem. 编辑2:糟糕,发现了问题。 I should have added UseSubmitBehavior="false" CausesValidation="false" to my Button. 我应该已经将UseSubmitBehavior="false" CausesValidation="false"到我的Button中。

You can go for something like from the below link which gives you two options for calling your JS function from code behind 您可以从下面的链接中找到类似的东西,该链接为您提供了两种选择, JS function从后面的代码调用JS function

Call JS function from code behind 从代码后面调用JS函数

Here the code is breaked down to call the js function 这里的代码被分解为调用js函数

ScriptManager.RegisterStartupScript(this, GetType(), "JSScript", "form_success(1);", true); 

UPDATE UPDATE

ClientScript.RegisterStartupScript(GetType(), "JSScript", "javascript:functionName(); ", true);

Hope that helps 希望能有所帮助

Oopsie, found the problem. 糟糕,发现了问题。 I should have added UseSubmitBehavior="false" CausesValidation="false" to my Button. 我应该已经将UseSubmitBehavior="false" CausesValidation="false"到我的Button中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM