How To Call Server Side Page Functions From Client Side Using VB.Net and JQuery

By NoseBagUK on 28/03/2010

Not many people are aware that you can call an ASP.Net function that is in your page code behind file from client side with a little bit of help from jQuery.

It basically involves exposing the function as a web method, in the same way as web services work. I find this method easier for tasks which are not repeated anywhere else in your application/site, as it is easier to maintain just the one file.

It's really easy to setup, just import the System.Web.Services namespace and then mark the function as a WebMethod which returns a string. The function must be a Shared function so it will not be able to access Session information or variables set in the page, if you need access to these then you must pass them through as parameters from the client.

    Imports System.Web.Services

    Public Class _Default
        Inherits System.Web.UI.Page

        <WebMethod()> _
        Public Shared Function SayHello(ByVal Name As String) As String
            Return "Hello " & Name & "!"
        End Function

    End Class

When this is done we can then call the function using jQuery's Ajax command.

First make sure that the latest version of jQuery is linked in you page header. Then set up the html below..

    <div>
        Enter you name:<br />
        <input type="text" id="txtName" value="Anonymous" />
        <input type="button" id="btnSayHello" />
    </div>

Then in the head section of the page add the Ajax call to the button. The important bit is that you change the url attribute to be the same as you page name and the function you want to call after the forward slash. You can pass parameters in the data attribute.

    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnSayHello').click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/SayHello",
                    contentType: "application/json; charset=utf-8",
                    data: "{'Name': '" + $('#txtName').val() + "'}",
                    dataType: "json",
                    success: function (result) {
                        alert(result.d);
                    },
                    error: function (result) {
                        alert("There was a problem with you Ajax call");
                    }
                });
            });
        });
    </script>

Easy as that, when I get round to it I will write another article on how you can use this method to return datasets as jSon which can be used in conjunction with jTemplate.

Comments RSS Feed

Add Comment

loading comments..