views:

3201

answers:

7

how Call 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 :

 [System.Web.Services.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...?

+2  A: 

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
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
A: 

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
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
+1  A: 

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
Ok ... thank U ......
Pramulia
A: 

hi my dear friends

i have this problem in another condition...

i have a little problem about using jquery...(i reeally do not know jquery but i forced to use it) i am using vs 2008 - asp.net web app with c# also i am using telerik controls in my pages also i am using sqldatasources (Connecting to storedprocedures) in my pages my pages base on master and content pages and in content pages i have mutiviews

=================================

in one of the views(inside one of those multiviews)i had made two radcombo boxes for country and city requirement like cascading dropdowns as parent and child combo boxes. i used old way for doing that , i mean i used update panel and in the SelectedIndexChange Event of Parent RadComboBox(Country) i Wrote this code :

protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)

{

hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue;

RadcomboboxCity.Items.Clear();

RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5"));

RadcomboboxCity.DataBind();

RadcomboboxCity.SelectedIndex = 0;

}

my child radcombo box can fill by upper code , let me tell you how : the child sqldatasource have a sp that has a parameter i i fill that parameter by this line -> hfSelectedCo_ID.Value = RadcbCoNameInInsert.SelectedValue;

RadcbCoNameInInsert.SelectedValue means country ID.

after doing that SelectedIndexChange Event of Parent RadComboBox(Country) could not be fire therefore i forced to set the autopostback property to true. afetr doing that every thing was ok until some one told me can u control focus and keydown of your radcombo boxes(when u press enter key on the parent combobox[country] , so child combobox gets focus -- and when u press upperkey on child radcombobox [city], so parent combobox[country] gets focus)(For Users That Do Not Want To Use Mouse for Input Info And Choose items) i told him this is web app , not win form and we can not do that. i googled it and i found jquery the only way for doing that ... so i started using jquery . i wrote this code with jquery for both of them :

<script src="../JQuery/jquery-1.4.1.js" language="javascript" type="text/javascript"></script>

<script type="text/javascript">

$(function() {

$('input[id$=RadcomboboxCountry_Input]').focus();

$('input[id$=RadcomboboxCountry_Input]').select();

$('input[id$=RadcomboboxCountry_Input]').bind('keyup', function(e) {

var code = (e.keyCode ? e.keyCode : e.which);

if (code == 13) {    -----------> Enter Key

$('input[id$=RadcomboboxCity_Input]').focus();

$('input[id$=RadcomboboxCity_Input]').select();

}

});

$('input[id$=RadcomboboxCity_Input]').bind('keyup', function(e) {

var code = (e.keyCode ? e.keyCode : e.which);

if (code == 38) {       -----------> Upper Key

$('input[id$=RadcomboboxCountry_Input]').focus();

$('input[id$=RadcomboboxCountry_Input]').select();

}

});

});

</script>

this jquery code worked BBBBBBUUUUUUUTTTTTT autopostback=true of the Parent RadComboBox Became A Problem , Because when SelectedIndex Change Of ParentRadComboBox is fired after that Telerik Skins runs and after that i lost parent ComboBox Focus and we should use mouse but we don't want it....

for fix this problem i decided to set autopostback of perentCB to false and convert

protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)

{

hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue;

RadcomboboxCity.Items.Clear();

RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5"));

RadcomboboxCity.DataBind();

RadcomboboxCity.SelectedIndex = 0;

}

to a public non static method without parameters and call it with jquey like this : (i used onclientchanged property of parentcombo box like onclientchanged = "MyMethodForParentCB_InJquery();" insread of selectedindexchange event)

public void MyMethodForParentCB_InCodeBehind()

{



hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue;

RadcomboboxCity.Items.Clear();

RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5"));

RadcomboboxCity.DataBind();

RadcomboboxCity.SelectedIndex = 0;

}

for doing that i read the blow manual and do that step by step :

http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=732

but this manual about static methods and this is my new problem ...

when i am using static method like :

public static void MyMethodForParentCB_InCodeBehind()

{



hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue;

RadcomboboxCity.Items.Clear();

RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5"));

RadcomboboxCity.DataBind();

RadcomboboxCity.SelectedIndex = 0;

}

so i recieved some errors and this method could not recognize my controls and hidden field...

any idea or is there any way to call non static methods with jquery(i know we can not do that but is there another way to solve my problem)???????????????

LostLord
A: 

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"&gt;

<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
Have you tried that?
John Saunders
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
A: 

By putting server side event into

//

//Put all your server side events into this.

//Including page_load or event related to button.

//

Above solution worked for me.

Remember to specify type and language into script tag and runat must be server.

Thanks`//

//Put all your server side events into this.

//Including page_load or event related to button.

//`

Developer.Vishal
A: 

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"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<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