如何在 Asp.net Button 单击后面从 C# 代码调用 javascript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9861321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a javascript function from c# code behind on Asp.net Button click?
提问by vini
I want to call my facebook send dialog function from code behind :
我想从后面的代码调用我的 facebook 发送对话框功能:
The javascript code is :
javascript代码是:
function facebook_send_message(to) {
FB.ui({
app_id:'*****',
method: 'send',
name: "*****",
link: '*****',
to: <%=to %>,
description:'sdf sdf sfddsfdd s d fsf s ',
redirect_uri: '******'
});
}
The twist here is i want to call this from a dynamically generated Aspx button
这里的扭曲是我想从动态生成的 Aspx 按钮调用它
Button btn = new Button();
btn.CssClass = "btn-add";
btn.Text = "Invite";
btn.Click += new EventHandler(btn_Click);
I tried this code on the button click
我在按钮单击时尝试了此代码
protected void btn_Click(object sender,EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "my", "function facebook_send_message(to);", true);
}
However it is not working Please help?
但是它不起作用 请帮忙?
采纳答案by Asdfg
Add it as an attribute.
将其添加为属性。
btn.attributes.add("OnClientClick", "javaScript: return myfunction(););
If OnClientClickdoesnt work, try onClick. Cant remember from top of my head which one will work.
如果OnClientClick不起作用,请尝试onClick。从我的头顶不记得哪个会起作用。
Make sure to return falsefrom the JS function to prevent Postback.
确保return false从 JS 函数中防止Postback.
Pseudo code:
伪代码:
--JS Function--
--JS函数--
function myFunction() {
alert('this is my fb function');
return false;
}
--Adding button in aspx.cs page--
--在aspx.cs页面添加按钮--
Button b = new Button();
b.ID = "btnSomeButton";
b.Text = "Call fb button";
dvButton.Controls.Add(b);
b.Attributes.Add("onclick", "return myFunction();");
You dont need btn_clickevent as you have in your code. You also dont need RegisterStartupScriptas you already have your function in JS file. RegisterStartupScriptis used when you want to add JS function to the page from the server side.
您不需要btn_click像代码中那样的事件。您也不需要,RegisterStartupScript因为您已经在 JS 文件中拥有您的功能。RegisterStartupScript当您想从服务器端向页面添加 JS 功能时使用。

