Various methods to call javascript function from asp.net code behind | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Various methods to call javascript function from asp.net code behind

Tuesday

Execute JavaScript function from ASP.NET code behind using c#:
                                              Calling a JavaScript function from codebehind is quiet simple. Here's how to do it. You can use ClientScript.RegisterStartupScript() to do what you want, like this:

 Declare a JavaScript function in your code as shown below.

Javscript:
<head runat="server">
    <title>Call JavaScript From CodeBehind</title>
    <script type="text/javascript">
        function fnSample() {
            alert('Codingcluster');
        }
    </script>
</head>
In order to call it from code behind, use the following code in your Page_Load

C# method 1:
protected void Page_Load(object sender, EventArgs e)
{
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "alert", "fnSample();", true);
    }
}

C# method 2:
protected void Page_Load(object sender, EventArgs e)
{
   ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "fnSample", "fnSample();", true);
}

C# method 3:

 protected void btnSubmit_Click(Object sender, EventArgs e)
    {
        var script = "alert('Hai codingcluster');";
        ClientScript.RegisterStartupScript(typeof(Page), "MyAlert", script, true);
    }
The format is (type, scriptKey, scriptText, wrapItInScriptTags).

                                     
The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind.

That's all. If this post is useful for you , please share this knowledge to your friends. Thanks!

5 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

Great delivery. Outstanding arguments. Keep up the great effort.
My page > dental implants problems

Anonymous said...

Good post. one more post like this http://aspnettutorialonline.blogspot.com/2012/09/javascript-design-patterns-book-free.html

Unknown said...

very userful.thanks...

Unknown said...

thanks a lot .. u can find java dumps here...http://www.allitcert.blogspot.com/2012/11/scjp-dumps-updated-question.html

Post a Comment

Share your thoughts here...

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets