19

How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?

As far as I know I can call static method in server side from client side...

server side:

 [WebMethod]
 public static void method1()
 {
 }

client side:

 <script language="JavaScript">
     function keyUP() 
     {
         PageMethods.method1();
     }
 </script>
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
 </asp:ScriptManager>

It works. Now how do I call non-static method from client side?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Pramulia
  • 191
  • 1
  • 1
  • 3

8 Answers8

18

You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.

1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)

2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx) Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.

<%@ WebService Language="C#" Class="SimpleService" %>

using System;
using System.Web.Services;

[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
    [WebMethod]
    public string GetMessage(string name)
    {
        return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
    }
} 

3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
     <script language="javascript" type="text/javascript">       
        function callServer() {
            SimpleService.GetMessage($get("Name").value, displayMessageCallback);
        }

        function displayMessageCallback(result) {
            $get("message").innerHTML = result;
        } 
    </script>


</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" >
            <Services>
                <asp:ServiceReference Path="~/SimpleService.asmx" />
            </Services>
        </asp:ScriptManager>
        <div>
        </div>
        <h1>Hello World Example</h1>

        <div>
            Enter Name: <input id="Name" type="text" />

            <a href="javascript:callServer()">Call Server</a>

            <div id="message"></div>
        </div>  
    </form>
</body>
</html>

I used the example I found from Scott Gu Found Here.

shawn deutch
  • 427
  • 1
  • 6
  • 10
  • I have tried this and its not working.....Is there any outer tool which i have to make it download? – Mitesh Jain Dec 24 '13 at 11:28
  • I'm looking to do something like the above, but I'm not sure what kinds of parameters I'm "allowed" to pass to my Web Service function from the JavaScript side. Ultimately, I'd like to pass the Page object, but I get all kinds of errors when I try to do that. Can I pass .NET objects, like things in the System.Web.UI.WebControls namespace? – LeeCambl Jul 25 '14 at 08:46
  • 2
    Note that you should no longer use ASMX - it's a legacy technology, just barely supported. The exact same thing can be done with WCF. – John Saunders Oct 05 '14 at 18:24
8

No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(

$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax

on server side:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Request.QueryString.HasKeys() || 
                string.IsNullOrEmpty(Request.QueryString["m"]))
    {
        //return error or something relevant to your code
    }
    var m = Request.QueryString["m"];

    switch(m)
    {
        case "a":
        a();
        break;
        .....
        .....
    }
}
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • OK i got it guys... so....................... do you have another solution how to call method in serverside(aspx.cs) from client side (aspx) guys..... thanks 4 solution...... – Pramulia Sep 01 '09 at 04:23
  • @theVillageldiot are you sure it is just ugly?or there is any thing else that we shuldnt use it this way? because I think this way of calling is better than using [web method].thanks any way. – vesna Nov 26 '12 at 08:34
2

Actually, you don't get to call non-static methods in this way.

When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • OK i got it guys... so....................... do you have another solution how to call method in serverside(aspx.cs) from client side (aspx) guys..... thanks 4 solution...... – Pramulia Sep 01 '09 at 04:22
2

C#

public string LoadString() {
    return "my string";
}

JS/jQuery

$('#txt').val(<%= LoadString() %>);
Mike
  • 623
  • 6
  • 26
1

as an answer to Pramulia i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)

<%@ Page Language="C#" AutoEventWireup="true"  %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html >
<head runat="server">
    <title>Client Callbacks</title>
    <script runat="server">
        public void RaiseCallbackEvent(String eventArgument)
        {
            // Processes a callback event on the server using the event
            // argument from the client.
        }

        public string GetCallbackResult()
        {
            // Returns the results of a callback event to the client.
            string dateString = DateTime.Now.ToLongDateString();

            return dateString;
        }

        void Page_Load(object sender, EventArgs e)
        {
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg",
                "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" +
                cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(),
                "CallServer", callbackScript, true);
        }
    </script>
    <script type="text/javascript">
        function ReceiveServerData(arg, context) {
            Message.innerText = "Date from server: " + arg;
        }
    </script>
</head>
<body>
    <h2>Client Callbacks Without Postbacks</h2>
    <form id="form1" runat="server">
       <input type="button" value="Callback" 
           onclick="CallServer('1', alert('Callback sent to Server'))" />
       <br />
       <span id="Message"></span>
   </form>
</body>
</html>
Kubi
  • 2,139
  • 6
  • 35
  • 62
  • i copied this from some microsoft web site. it works fine and gets a string from serverside to client sidee however i need a solution which triggers serverside non static method from a javascript. – Kubi Mar 29 '10 at 08:12
1

If you want to call it using the same function, you can use the following code:

[WebMethod]
public static void method1()
{
    ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
    obj.yourFunctionName(ParametersIfAny);
}
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
0

I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.

Bbb
  • 517
  • 6
  • 27
-5

Dave has written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).

C# Code:

[WebMethod]
public static string yourmethod(/*params*/)
{
   return "Hello World!"   
}

ASPX:

$.ajax({
    type: 'POST',
    data: /*Your Data*/,
    dataType: 'JSON',
    contentType: 'application/json',
    url: '/yourpage.aspx/yourmethod',//Method to call
    success: function(result, status) {
        //handle return data
    },
    error: function(xhr, status, error) {
        //handle error
    }
});
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188