How to call a javascript function from c# code behind on Asp.net Button click?
59,456
Add it as an attribute.
btn.attributes.add("OnClientClick", "javaScript: return myfunction(););
If OnClientClick
doesnt work, try onClick
. Cant remember from top of my head which one will work.
Make sure to return false
from the JS function to prevent Postback
.
Pseudo code:
--JS Function--
function myFunction() {
alert('this is my fb function');
return false;
}
--Adding button in aspx.cs page--
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_click
event as you have in your code. You also dont need RegisterStartupScript
as you already have your function in JS file. RegisterStartupScript
is used when you want to add JS function to the page from the server side.
Comments
-
vini almost 4 years
I want to call my facebook send dialog function from code behind :
The javascript code is :
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
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?