How to call a C# code behind method from a Java Script function

Posted by Sabarimahesh under C# category on | Points: 40 | Views : 8395
<html xmlns="" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function TestCodeBehind()
document.getElementById('<%= Label1.ClientID %>').innerHTML = '<%= CodeBehind() %>';
return false;

function TestCodeBehind2()
document.getElementById('<%= Button2.ClientID %>').click();
// return false;


<form id="form1" runat="server">
<input id="Button1" type="button" value="Sample One" onclick="javascript:TestCodeBehind()" />
<input id="Button3" type="button" value="Sample two" onclick="javascript:TestCodeBehind2()" />
<asp:Button ID="Button2" runat="server" Text="" OnClick="ClickedME" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>


protected void Page_Load(object sender, EventArgs e)
Button2.Attributes.Add("style", "visibility :hidden");

protected string CodeBehind()
return "this is a string from C# code behind " + DateTime.Now.ToString();
protected void ClickedME(object sender, EventArgs e)
Label1.Text = "You clicked this button on " + DateTime.Now.ToString();

Comments or Responses

Posted by: Yvonne on: 9/4/2012 Level:Starter | Status: [Member] | Points: 10
<The reason I asked is coz I have lots of dynamic Buttons declared code-behind in my project, not from design page.>
Only one case is NOT working if "Button2" is declared in code-behind Page_Load instead from .aspx page ...
// <asp:Button ID="Button2" runat="server" Text="" OnClick="ClickedME" />

I wonder if you have any solution for my case?

protected void Page_Load(object sender, EventArgs e)
Button Button2 = new Button();
Button2.ID = "Button2";
Button2.Click += new EventHandler(this.ClickedME);
Button2.Attributes.Add("OnClick", "ClickedME"); // I cannot find any oOnClick method to Button2, guess it's the problem

.aspx page

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="main">
<asp:Panel ID="hiddenPanel" runat="server">

Login to post response