Skip to main content

How to call ASP.Net page method with jQuery

In this blog post we are going to learn about how we can call asp.net page methods from jQuery.

What is ASP.Net Page Method?


Page methods are available from ASP.Net 2.0. It’s an alternative to web services in ASP.Net application. This methods are exposed at client side and you can call that page methods directly from JavaScript.It is an easy way to communicate asynchronously with the server using Ajax.

Creating a page method:


So for creating a page method let’s create a asp.net web empty web application.

Calling asp.net page methods with jquery


Now we are ready with our application let’s write a simple hello world page method.

using System;
using System.Web.Services;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string HelloWorld()
        {
            return "Hello World";
        }
    }
}
Now our server side code is ready It’s time to write some code for html.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" 
    Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Calling Page Method with jquery</title>
    <script type="text/javascript" src="Scripts/jquery-2.0.0.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div id="HelloWorldContainer">
    
    </div>
    </form>
</body>
</html>
Now in the above HTML code you have seen we have included the jQuery min JavaScript file with script tag and then I have created a script manager with EnabledPageMethods as true. Please note that scriptmanager is required here to call page methods from JavaScript. Also I have created a div with Id “HelloWorldContainer” to print output of HelloWorld page method.

Calling page method from jQuery:

Now our HTML and server side code is ready. So it’s time to write some JavaScript code. Following is a code for calling a page method from JavaScript.

<script type="text/javascript">
    $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#HelloWorldContainer").text(msg.d);
                }
            });
    });
</script>

Here in the above code you have seen that I have written code in document ready function of jQuery which will called when page will be loaded and with jQuery Ajax function I have called page method and replace the text of div with the reply from Page method. Now when you run this in browser. It’s look like following.

Calling a page method from jquery

You can see It’s a very easy to call a page method in jQuery. Hope you like it. Stay tuned for more..

Comments

  1. Technically you are calling a web method and not a page method. Am more interested in seeing how you call ASPX Page method and not WebMethod.

    ReplyDelete
  2. Sanket - First of all asp.net web services and asp.net page methods are different. If you don't know the difference here is the link -

    http://stackoverflow.com/questions/6604050/differences-between-doing-ajax-using-a-page-method-a-web-service-and-a-custom-h

    For web service you need different file .asmx and page method you don't need to create separate file. It's an asp.net ajax functionality and Microsoft it self uses term as page method.

    Yes, It's similar to web services web method attribute. Because here also we have web method attribute. But that does not mean it's a web service.



    And There is no way to directly call a server side method. Either you have to use page method or you need to implement call back interface.

    ReplyDelete
  3. Please see my wordings clearly - I said you are calling WebMethod. I never said as a Web Service. Never mind - mistakes do happen.

    Secondly, your method is static.Is there a way I can differentiate between sessions across users?

    ReplyDelete
  4. Sanket, I have not made mistake.You are leading this conversation in wrong direction.I think you are mixing terms and getting confused. This asp.net page methods are there from ASP.NET 2.0. This is provides by default with script manager. The methods you are talking about is called "Server side methods" which we are write in .cs file. It is not called Pagemethods.


    This is same like comparing WCF with Windows Azure where both are separate entities.

    There is no direct way to call server side method from javascript. There are workaround like creating static method and writing server brackets like <%=YourMethodName()%> . But it does not work on all the scenario and many drawbacks.

    Regarding session, Yes, You can use session in page methods. See the this link- http://stackoverflow.com/questions/5554718/set-session-in-pagemethod-asp-net

    But If you are calling multiple page method same time asyc way then you can not modify session it should be in read only-http://stackoverflow.com/questions/4506273/make-session-readonly-on-asp-net-programmatically-enablesessionstate-readonly



    If you not make this session read only then it will call one by one.


    I hope my answers will satisfy your query.


    Regards,
    Jalpesh

    ReplyDelete
  5. Its your call. It seems you are hurt by the statement. I've not mixed the terms - that's what I know.

    ReplyDelete
  6. http://stackoverflow.com/questions/4264039/page-method-vs-web-service

    http://forums.asp.net/t/1381378.aspx/1



    Those are my clear readings...Those articles give clear answer to my question.


    Anyways, thanks for your attempt. :)

    ReplyDelete
  7. Well I never hurt by any comments. It's my duty to answer comments !!

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. There was a time when sharing knowledge was considered a noble contribution... but alas! nowadays it is just becoming a platform to display or hurt egos

    guys, play a fair game :P

    ReplyDelete

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…