[ACCEPTED]-Call non-static method in server-side from client-side using JavsScript-webmethod

Accepted answer
Score: 18

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

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

2) SIMPLESERVICE.ASMX 8 - Add a new .asmx web service (I called 7 mine SimpleService.asmx) Notice the [System.Web.Script.Services.ScriptSerive] decoration 6 and that the SimpleService class implements 5 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 4 the service in you script manager and you 3 are off and running. In my Javascript I 2 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 1 used the example I found from Scott Gu Found Here.

Score: 8

No you cannot call non-static methods from 7 client side per se. I've tried it once but 6 it is ugly one (also I used jQuery ajax). Just 5 call the page using ajax with method name 4 appended to it as query string parameter 3 and then on server side check the parameter 2 and call the relevant method. But as I've 1 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;
        .....
        .....
    }
}
Score: 2

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

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

Score: 2

C#

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

JS/jQuery

$('#txt').val(<%= LoadString() %>);

0

Score: 1

as an answer to Pramulia i think you want 3 to have a function with an argument from 2 the client side which is implemented in 1 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>
Score: 1

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

[WebMethod]
public static void method1()
{
    ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
    obj.yourFunctionName(ParametersIfAny);
}
Score: 0

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

More Related questions