Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling a code-behind function from JavaScript

4.04/5 (21 votes)
14 Apr 2011CPOL3 min read 187.8K  
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)