Call non-static method in server-side from client-side using JavsScript
Asked Answered
A

8

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?

Assr answered 1/9, 2009 at 2:24 Comment(0)
J
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.

Januarius answered 6/5, 2010 at 17:28 Comment(3)
I have tried this and its not working.....Is there any outer tool which i have to make it download?Derbent
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?Humphreys
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.Aweinspiring
R
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;
        .....
        .....
    }
}
Riemann answered 1/9, 2009 at 3:55 Comment(2)
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......Assr
@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.Benioff
A
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.

Aweinspiring answered 1/9, 2009 at 3:56 Comment(1)
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......Assr
T
2

C#

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

JS/jQuery

$('#txt').val(<%= LoadString() %>);
Tedium answered 29/7, 2015 at 20:15 Comment(4)
you can use protected instead of public.Tedium
I'm pretty sure this will not work since LoadString is not a static function.Disgrace
yes it works for the question at hand. The method does not have to be static because the partial class was already initialized.Tedium
Nevermind, I hadn't realised it is WebService Class, I think that is the only situation in which a WebMethod can be declared without being static.Disgrace
E
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>
Eleven answered 29/3, 2010 at 2:32 Comment(1)
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.Eleven
I
0

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);
}
Inlier answered 26/7, 2016 at 9:5 Comment(0)
P
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.

Panfish answered 23/4, 2018 at 15:54 Comment(0)
R
-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
    }
});
Riemann answered 1/9, 2009 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.