gvd
gvd

Reputation: 1592

How can I Call Code Behind Method from JavaScript

I'm have few days reading and searching an answer for this question but I don't found.

I'm using this code

$('#Button1').click(function () {
            $.ajax({
                type: "POST",
                url: "/Default.aspx/ServerSideMethod",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                cache: false,
            })
            return false;
        });
        });

for try to call C# Method

[WebMethod]
 public void ServerSideMethod() {//Do something}

But I could not found any solution that work....

Upvotes: 0

Views: 9194

Answers (5)

Rudy
Rudy

Reputation: 2353

Try this in js:

$('#Button1').click(function () {
        // this calls default.aspx 
        $.ajax({
            type: "POST",
            url: '/Default.aspx',
            data: "{ServerSideMethod : '1'}", // send a parameter, to tell it what we want
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            function(data){
                // data is json sent from server, if not, try $.parseJSON(data)
                // do something here after the server side code has finished
                if(data.ok){
                    //success from server side
                }
            }  
        });
        return false;
    });
    });

And in Default.aspx.cs:

    // fires anytime default.aspx is loaded
    protected void Page_Load(object sender, EventArgs e)
    {
        // check if is ajax call and not normal page load in the browser
        if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
             Response.Clear();  //empty everithing so we don't send mixed content
             // no cache on ajax, IE caches ajas if this is missing
             Response.Cache.SetExpires(DateTime.Today.AddMilliseconds(1.0));
             Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
             // here we are checking what we want to do, what client side asked
             if(!string.IsNullOrWhiteSpace(Request["ServerSideMethod"])) // this will be "1"
             {
                  doAll(); // do your work
             }
             Response.End();
        }
    }

    private void doAll() 
    {
            // do work, then send some json, as this is what you expect         
            // JavaScriptSerializer is located in System.Web.Script.Serialization
            Response.Write(new JavaScriptSerializer().Serialize(new { ok = 1, error = 0 }));
    }

Upvotes: 1

sm.abdullah
sm.abdullah

Reputation: 1802

asp.net Markup

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>


</head>
<body>
    <form id="form1" runat="server">
    <%--
     you can remove dropdown if asp.net Render __doPostBack already for You.
    --%>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
    </asp:DropDownList>

    <input type="button" value="Click Me" onclick="__doPostBack('CallFromJavaScript','Message from JavaScript')" />

    </form>
</body>
</html>

and Code Behinde.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                string funcationName = Request.Params["__EVENTTARGET"];
                string org = Request.Params["__EVENTARGUMENT"];
                if (funcationName == "CallFromJavaScript")
                {
                    CallFromJavaScript(org);
                }
            }
        }


        protected void CallFromJavaScript(string Data)
        {
            Response.Write(DateTime.Now);
        }


    }
}

May be This Trick help full For You

Upvotes: -1

Saranya
Saranya

Reputation: 2008

If you want to call a non static method from ajax, I suggest you to create a web service and call it from javascript. You can have non static methods inside a web service.

There are quite a lot of examples in Stackoverflow on how to call a web service from javascript. Call ASP.NET web service method from JavaScript

Upvotes: 0

Siva Tumma
Siva Tumma

Reputation: 1701

first of all I would suggest you to write some debug statements. write some output in the first lines of doAll(). it will in fact lets you know if you are really sending the request from the browser to your server. I mean if there is any link to your server at the url: "/Default.aspx/ServerSideMethod",. I am thinking you are doing ajax call but you are not starting the server at all OR there is no listener that links this URL to your method.

Upvotes: 0

Ric
Ric

Reputation: 13248

For it to work, ensure that the method location set in url is correct and that the method is public and static and that is has a [WebMethod] attribute added such as:

[WebMethod]
public static void doAll()
{
    //do something
}

if the url is "/Default.aspx/ServerSideMethod" then your method should look like this:

[WebMethod]
public static void ServerSideMethod()
{
    //do something
}

Upvotes: 3

Related Questions