Call non-static method in server-side from client-side using JavsScript
Solution 1:
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.
Solution 2:
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;
.....
.....
}
}
Solution 3:
C#
public string LoadString() {
return "my string";
}
JS/jQuery
$('#txt').val(<%= LoadString() %>);