Click here to Skip to main content
Click here to Skip to main content

Calling a code-behind function from JavaScript

, 14 Apr 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to run server side code called from JavaScript, receive a result, and update your web page.


I've been searching in CodeProject for an article about this same topic, and couldn't find something exactly about this, so I hope this could help someone.

As the title of this post says, today I want to share how to call a function or method in the code-behind from JavaScript, or in other words, run some server side code called from the client and then update our web page.


I needed to add some functionality to some ASPX pages so they would look more responsive, more like a desktop app. The thing is that I did not want to write the functionality in JavaScript. I wanted to implement something a little bit complex, but as I already coded it in code-behind, I thought I'd try to rewrite it in JavaScript if it is possible to call a function or method from it (in this case).

Simple Scenario

Let's imagine the following simple scenario, just for the purpose of showing how we can achieve our goal today. Imagine that we have two text boxes: txtName and txtLastName. We want the user to write his full name and then greet him with a message when the last text box loses focus.

We could easily do this all in JavaScript, but remember that it is just for the purpose of demonstrating how to call a server side method from the client side and update our web page.

Using the code

OK. Let's add three text boxes to our ASPX page:

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>

Now, inside our body tag, let's add some JavaScript:

<script type="text/javascript">
    function greet(txtN, txtLastN, txtMsg){
        var ctrlN = document.getElementById(txtN);
        var ctrlLastN = document.getElementById(txtLastN);
        var fullName = ctrlN.value + '  ' + ctrlLastN.value;
        PageMethods.greetUser(fullName, greetSuccess, greetFailed, txtMsg);
    function greetSuccess(res, txtMsg) {
        var ctrlTxtMsg = document.getElementById(txtMsg);
        ctrlTxtMsg.value = res;
    function greetFailed(res, dst) {

We just created three functions:

  • Greet: Receives the ClientId of the txtName, txtLastName, and txtMsg textboxes. Then it gets the objects for txtName and txtLastName, concatenates their value, and calls the code-behind function "greetUser". We are passing to that function four values: the full name we've got by concatenating the txtName and txtLastName values, the function which will be called if everything goes OK, the function which is going to be called if something fails, and we can pass whatever we want in the last parameter, in this case, the ClientId of the txtMsg text box. Notice that "greetUser" is our code-behind function and that we are using PageMethods to access it.
  • GreetSuccess is the function that is going to be called if everything goes OK. Receives the result of the code-behind function and a parameter: the ClientID of the txtMsg text box, so we can get the object itself and assign to it the result of the code-behind function as its value.
  • GreetFailed: Receives the same two parameters as GreetSuccess. In this case, we are just going to show an alert with the error that happened.

Now, let's see our code behind. First, in our Page_Load method, we'll add:

If Page.IsPostBack = False Then
    txtLastName.Attributes.Add("onblur", "javascript:greet('" & _
       txtName.ClientID & "','" & txtLastName.ClientID & "','" & _
       txtMsg.ClientID & "')")
End If

Why am I assigning the attribute "onblur" to our txtLastName text box in our code instead of doing it directly in the ASPX page? Just for demonstration. You could add this attribute from the ASPX page, but if you have a more complex scenario, let's say a GridView, or a DataList with DataTemplates, or if you are creating controls dynamically... then you could for example get the control you need from code in the GridView_DataBound method or in the function you are creating your dynamic layout, and call the JavaScript function the way it is shown above.

OK, here comes the important part of the article. The code behind function that we are calling from JavaScript:

<System.Web.Services.WebMethod()> _
Public Shared Function greetUser(ByVal fullName As String) As String
    Return "Welcome " & fullName & "!"
End Function

Please notice that we are giving this function the System.Web.Services.WebMethod attribute; this is the reason why we can access this function from JavaScript using PageMethods. In this function, we are receiving the full name that we got by joining the values from txtName and txtLastName in our "Greet" JavaScript function.

Final Words

I guess that's it. This was a really simple scenario, but you could think of really complex operations inside a GridView. As ever, please feel free to leave your comments, questions, suggestions, or whatever you want to tell. You can also read the original post from my blog.

Thanks for reading!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Team Leader
Spain Spain
No Biography provided
Follow on   Twitter

Comments and Discussions

QuestionNot working PinmemberMember 962536023-Nov-12 8:43 
GeneralMy vote of 3 Pinmemberomvikram13-May-12 1:40 
GeneralMy vote of 3 PinmemberShining Legend23-May-11 18:52 
AnswerRe: My vote of 3 Pinmembernereo.lopez13-Jun-11 21:38 
GeneralRe: My vote of 3 PinmvpAspDotNetDev18-Jun-11 23:10 
GeneralMy vote of 3 PinmvpAspDotNetDev20-May-11 22:56 
General6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download PinmvpAspDotNetDev20-May-11 18:04 
GeneralRe: 6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download Pinmembernereo.lopez20-May-11 22:30 
GeneralRe: 6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download PinmvpAspDotNetDev20-May-11 22:47 
GeneralVery Good PinmemberOmar Gamil15-May-11 3:46 
AnswerRe: Very Good Pinmembernereo.lopez15-May-11 5:14 
Generalthanks for sharing PinmemberPranay Rana24-Apr-11 21:15 
GeneralRe: thanks for sharing Pinmembernereo.lopez25-Apr-11 3:13 
QuestionAccess SQL database in Javascript Pinmemberfcis201020-Apr-11 11:42 
AnswerRe: Access SQL database in Javascript Pinmembernereo.lopez23-Apr-11 0:34 
GeneralRe: Access SQL database in Javascript Pinmemberfcis201023-Apr-11 2:10 
AnswerRe: Access SQL database in Javascript Pinmembernereo.lopez23-Apr-11 7:29 
GeneralMy vote of 5 Pinmembercws2_na19-Apr-11 16:47 
GeneralRe: My vote of 5 Pinmembernereo.lopez19-Apr-11 22:27 
GeneralMy vote of 5 Pinmembermutex_semaphore17-Apr-11 14:23 
GeneralRe: My vote of 5 Pinmembernereo.lopez19-Apr-11 22:32 
Hey Thanks! Hope you can take advantage of it! Smile | :)
GeneralIT GOOD BUT... Pinmemberkhamis14-Apr-11 12:51 
GeneralRe: IT GOOD BUT... Pinmembernereo.lopez19-Apr-11 22:33 
GeneralTry AJAX PinmemberCorey Fournier14-Apr-11 8:30 
GeneralRe: Try AJAX Pinmembernereo.lopez19-Apr-11 22:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 14 Apr 2011
Article Copyright 2011 by nereo.lopez
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid