Call .NET Code Behind from jQuery

In this task we want to call a pages code behind from jQuery without the requirement of a full web services pages.  First off this will not replace the need for web services (the question came up) and this should be used sparingly.

First thing is to setup the code behind for the page, in this example we are using the Default.aspx page and create plus link a Local.js file.  In this example I am showing how values can be passed in.

Code Behind for Default.aspx.cs

using System.Web.Services;

public partial class _Default : Page
public static string TestValue(int firstValue, int secondValue, string someValue)
// Do something funky
var funky = firstValue + secondValue;
var newValue = string.Format("{0} {1} + {2} is equal to {3}", someValue, firstValue, secondValue, funky);
return newValue;

Notice that in order to use [WebMethod] that a using statement is needed for System.Web.Services.  Secondly all WebMethods in page have to be static.  If it is not static you will get a 500 error.

In the Default.aspx page add a button (can be any button)

<!—in the header –>
<script src="" type="text/javascript"></script>
<script src="Scripts/Local.js" type="text/javascript"></script>

<!—in the content –>
<button id="SomethingFunky">Do It</button>

Now open up that Local.js file and add the following

    $("#SomethingFunky").click(function () {
        var firstValue = 2
        var secondValue = 2
        var someValue = "The value of"
        var values = '{"firstValue":"' + firstValue + '","secondValue":"' + secondValue + '","someValue":"' + someValue + '"}';
            type: "POST",
            url: "Default.aspx/TestValue",
            data: values,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
            error: function (xml, textStatus, errorThrown) {
                alert(xml.status + "||" + xml.responseText);

So what will happen is that when the button is clicked, an ajax call is sent to the code behind method.  If everything is successful you should get an alert box with the first numbers added together.  If not, an error is displayed with the reason for the failure.

This entry was posted in Web and tagged , . Bookmark the permalink.