Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET

Calling a code-behind function from JavaScript

Rate me:
Please Sign up or sign in to vote.
4.04/5 (21 votes)
14 Apr 2011CPOL3 min read 183.1K   42   28
How to run server side code called from JavaScript, receive a result, and update your web page.

Introduction

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.

Background

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.NET
<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:

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) {
        alert(res.get_message());
    }
</script>

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:

VB
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:

VB
<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!

License

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


Written By
Team Leader
Spain Spain
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThanks! Pin
Member 141647028-Sep-21 3:03
Member 141647028-Sep-21 3:03 
Questionthis code will not work, unless you add script manager tag Pin
Gulati Aman25-Jun-15 18:33
Gulati Aman25-Jun-15 18:33 
QuestionNot working Pin
mohammed s23-Nov-12 7:43
mohammed s23-Nov-12 7:43 
GeneralMy vote of 3 Pin
omvikram13-May-12 0:40
omvikram13-May-12 0:40 
GeneralMy vote of 3 Pin
Shining Legend23-May-11 17:52
Shining Legend23-May-11 17:52 
AnswerRe: My vote of 3 Pin
nereo.lopez13-Jun-11 20:38
nereo.lopez13-Jun-11 20:38 
GeneralRe: My vote of 3 Pin
AspDotNetDev18-Jun-11 22:10
protectorAspDotNetDev18-Jun-11 22:10 
GeneralMy vote of 3 Pin
AspDotNetDev20-May-11 21:56
protectorAspDotNetDev20-May-11 21:56 
General6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download Pin
AspDotNetDev20-May-11 17:04
protectorAspDotNetDev20-May-11 17:04 
GeneralRe: 6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download Pin
nereo.lopez20-May-11 21:30
nereo.lopez20-May-11 21:30 
GeneralRe: 6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download Pin
AspDotNetDev20-May-11 21:47
protectorAspDotNetDev20-May-11 21:47 
GeneralRe: 6 Similar Articles / No Mention of ScriptManager or EnablePageMethods / No Download Pin
Member 141647028-Sep-21 7:43
Member 141647028-Sep-21 7:43 
GeneralVery Good Pin
Omar Gameel Salem15-May-11 2:46
professionalOmar Gameel Salem15-May-11 2:46 
AnswerRe: Very Good Pin
nereo.lopez15-May-11 4:14
nereo.lopez15-May-11 4:14 
Generalthanks for sharing Pin
Pranay Rana24-Apr-11 20:15
professionalPranay Rana24-Apr-11 20:15 
GeneralRe: thanks for sharing Pin
nereo.lopez25-Apr-11 2:13
nereo.lopez25-Apr-11 2:13 
QuestionAccess SQL database in Javascript Pin
fcis201020-Apr-11 10:42
fcis201020-Apr-11 10:42 
AnswerRe: Access SQL database in Javascript Pin
nereo.lopez22-Apr-11 23:34
nereo.lopez22-Apr-11 23:34 
GeneralRe: Access SQL database in Javascript Pin
fcis201023-Apr-11 1:10
fcis201023-Apr-11 1:10 
AnswerRe: Access SQL database in Javascript Pin
nereo.lopez23-Apr-11 6:29
nereo.lopez23-Apr-11 6:29 
GeneralMy vote of 5 Pin
cws2_na19-Apr-11 15:47
cws2_na19-Apr-11 15:47 
GeneralRe: My vote of 5 Pin
nereo.lopez19-Apr-11 21:27
nereo.lopez19-Apr-11 21:27 
GeneralMy vote of 5 Pin
mutex_semaphore17-Apr-11 13:23
mutex_semaphore17-Apr-11 13:23 
GeneralRe: My vote of 5 Pin
nereo.lopez19-Apr-11 21:32
nereo.lopez19-Apr-11 21:32 
GeneralIT GOOD BUT... Pin
khamis14-Apr-11 11:51
khamis14-Apr-11 11:51 

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

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