AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / Call JavaScript Function from Code-behind in Asp.net C# Vb

Call JavaScript Function from Code-behind in Asp.net C# Vb

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Oct 10, 2020

In my previous tutorials, I’d explained how to show alert message from javascript, how to show alert message from code-behind, confirm message box example using javascript and other more cracking tutorials on Asp.net, JavaScript, jQuery here.

Now here in this tutorial, I’ll explain how to call javascript function from code-behind or server-side in asp.net using c# or vb.net with example code.

To call javascript function from code-behind, we need to use ScriptManager.RegisterStartupScript() method. Here is the syntax for this method:

ScriptManager.RegisterStartupScript(Control control, Type type,string key, string script,
bool addScriptTags);

Call JavaScript Function from Code-behind or Server-side

Following is the complete HTML Markup code that I used in my .aspx page to call javascript function from code-behind:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Call JavaScript function from code-behin in Asp.net</title>
<script type=”text/javascript”>
function myFunction() {
//some code here
alert(‘Function called successfully!’);
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<h4>
Call JavaScript function from code-behin in Asp.net</h4>
<div>
<asp:Button ID=”btnServerSide” runat=”server” OnClick=”btnServerSide_Click”
Text=”Call Function” />
</div>
</form>
</body>
</html>

As you can see from above code, I used OnClick event as OnClick=”btnServerSide_Click” to call javascript function from code-behind or server-side. Now define that event in code-behind as shown below.

Call JavaScript Function From Server-side In C#

//Following statement is used to call pre-defined javascript function
protected void btnServerSide_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), “myFunction”, “myFunction();”, true);
}

OR

If you are dealing with asp.net UpdatePanel and UpdateProgress, use the following code:

//Following statement is used to call pre-defined javascript function
protected void btnServerSide_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(myUpdatePanelID, myUpdatePanelID.GetType(),
“myFunction”, “myFunction();”, true);
}

Call JavaScript Function From Server-side In Vb.net

‘Following statement is used to call pre-defined javascript function
Protected Sub btnServerSide_Click(ByVal sender As Object, ByVal e As EventArgs)
ScriptManager.RegisterStartupScript(Me, Me.GetType(), “myFunction”, “myFunction();”, True)
End Sub

OR

If you are dealing with asp.net UpdatePanel and UpdateProgress, use the following code:

‘Following statement is used to call pre-defined javascript function
Protected Sub btnServerSide_Click(ByVal sender As Object, ByVal e As EventArgs)
ScriptManager.RegisterStartupScript(myUpdatePanelID, myUpdatePanelID.GetType(),
“myFunction”, “myFunction();”, True)
End Sub

Example Result

How to javascript function from code-behind in asp.net c# vb.net?

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Comments

  1. SR says

    Jun 19, 2017 at 6:24 PM

    myFunction() is calling on each time when page refreshing and alert is displaying on each page load.
    It is happening after we use it first time. How to solve this problem ?

    Reply
    • Mayank Modi says

      Jun 19, 2017 at 7:24 PM

      What do you mean by displaying on each page load? The example referring to onclick event. Did you prepared jsfiddle or something to check what you’re doing?

      Reply
  2. Bryan says

    Jul 25, 2015 at 2:35 AM

    Thanks For the information.. it was very important for me.

    Reply
  3. Ram Samuj says

    Jun 07, 2015 at 2:35 PM

    if javascript function is return type then how can call on btn click

    and how we catch return value

    Reply
    • Mayank Modi says

      Jun 07, 2015 at 4:55 PM

      Check my last reply to Xehanort.

      Reply
  4. Xehanort says

    Apr 07, 2015 at 8:59 AM

    Hi, thanks for the info.

    I need to get the return value from the js function, how do i do this in vb,net code behind?

    Reply
    • Mayank Modi says

      Apr 07, 2015 at 7:48 PM

      Hi Xehanort,

      As basis of this, you can’t get value directly in code-behind because your client-side code executes on client-side and server-side code executes server-side, those two parts of code never call one another, right?

      But don’t worry, we have hiddenfield that do work for us. What you need to do is set hiddenfield value (using JavaScript/jQuery) and retrieve that value server-side.

      Here is a workaround, you can check for the reference: http://www.codeproject.com/Questions/228944/Can-i-get-value-from-javascript-in-Csharp-code-beh

      Reply
  5. Chris Schryer says

    Feb 11, 2015 at 2:40 AM

    I’m calling a JS fcn that fires AJAX to a webmethod and returns a boolean. How do I retrieve the return value in the codebehind? (VB) I can set a hiddenfield value in the JS, but if it’s async how can my VB know when it’s changed?

    Reply
    • Mayank Modi says

      Feb 13, 2015 at 8:50 PM

      You can ofcource use hiddenfield as runat=”server” and update its value via jQuery and retrieve its updated values from server-side by using “hdnField.Value” (you will get string value so if you need bool then convert it to boolean) as VB code.

      Reply
      • Chris Schryer says

        Feb 13, 2015 at 8:54 PM

        It’s asynchronous. How does my code behind know when to get the value without a postback?

      • Mayank Modi says

        Feb 13, 2015 at 9:07 PM

        You need to use update panel for asynchronous callbacks and also put that hiddenfield to update panel. So whenever you call asynchronous callbacks, your update panel also get updated.

      • Chris Schryer says

        Feb 13, 2015 at 9:12 PM

        The client side value change does not cause postback. nevermind, thanks for trying. I just replicated the webmethod in the code behind.

      • Mayank Modi says

        Feb 13, 2015 at 9:15 PM

        I also means same think by using update panel but in different approach. Nevermind, thanks for posting comments. 🙂

  6. Jason Timmins says

    Nov 20, 2014 at 10:50 PM

    That’s really great but after I call my JavaScript function using RegisterStartupScript my UpdateProgress panel stops working. Does the RegisterStartupScript call damage the other JS that’s on the page… the JS that came with the ASP.NET controls? Any thoughts?

    Reply
    • Mayank Modi says

      Nov 21, 2014 at 11:48 AM

      I think it should work even with “UpdatePanel” and “UpdateProgress”. If its not working then check the post again, I updated my post.

      Let me know it works for you?

      Reply
      • Jason Timmins says

        Nov 25, 2014 at 1:56 PM

        Still no joy. It seems that if I call the function when the UpdateProgress panel is open, the panel never closes.

Leave a Reply Cancel reply

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,098 Followers
  • 51 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Asp.net TextBox: How to Get Set TextBox Value or Text in JavaScript
  • Show Alert Message Box from Code-behind in Asp.net C# Vb
  • Show Confirm Message Box from Code-behind in Asp.net
  • Top 10 OOPS Concepts In C# .NET With Examples

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous Show Alert Message Box from Code-behind in Asp.net C# Vb
Next Prompt Alert Before Page Leave in JavaScript or jQuery