Monday, August 12, 2013

ASP.NET Call JavaScript function from CodeBehind

A small tips about how to call JavaScript function or method from Code Behind
My JavaScript Code:


<script type="text/javascript">
   function sayHellobtn() {
            alert("Hello!! Method called from code behind button click...!!!")
   } 
</script>
Method 1:
We can call above method sayHellobtn()  from code behind on ASP button click event:Add Button click event:


protected void btn_callJS_Click(object sender, EventArgs e)
{
        btn_callJS.Attributes.Add("onclick", "sayHellobtn()");
}
//Note: btn_callJS is Button ID;

Method 2: 

 We can add ASP button control properties onclientclick to call JavaScript Method:


<asp:Button ID="btn_callJS" runat="server" Text="Call JS Function"
            onclick="btn_callJS_Click" onclientclick="sayHellobtn()" />

Method 3:

We can do this by adding below code on Code Behind to call JavaScript function:

ScriptManager.RegisterClientScriptBlock(Page,this.GetType(),"Script","sayHellobtn()", true);

e.g:

protected void btn_callJS_Click(object sender, EventArgs e)
{
    //btn_callJS.Attributes.Add("onclick","sayHellobtn()");       ScriptManager.RegisterClientScriptBlock(Page,this.GetType(),"Script","sayHellobtn()",true);
}

References: MSDN  ClientScriptManager.RegisterClientScriptBlock Method             

No comments:

Post a Comment

http://myaspdotnetworld.blogspot.com