c# - How can I Call Code Behind Method from JavaScript - Stack Overflow

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

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....

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....

Share Improve this question edited Nov 1, 2013 at 12:55 gvd asked Nov 1, 2013 at 12:44 gvdgvd 1,6027 gold badges33 silver badges60 bronze badges 8
  • I think your using plain asp?! Where does the method live? – Silvermind Commented Nov 1, 2013 at 12:47
  • Sorry... I'm using WebForms. The Method is in the code behind... – gvd Commented Nov 1, 2013 at 12:49
  • Show us the method. I believe it should be static and marked with the [WebMethod] attribute. – Sir Crispalot Commented Nov 1, 2013 at 12:50
  • The problem with [WebMethod] and static Method is I cannot access to non-static Method and can manage database connections... I need use none-static method... – gvd Commented Nov 1, 2013 at 12:53
  • you cannot use non-static methods for webmethods and thus non-static methods within the body of the method itself. – Ric Commented Nov 1, 2013 at 12:57
 |  Show 3 more ments

5 Answers 5

Reset to default 3

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
}

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 }));
    }

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.

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

asp Markup

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

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


</head>
<body>
    <form id="form1" runat="server">
    <%--
     you can remove dropdown if asp 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745260922a4619209.html

相关推荐

  • c# - How can I Call Code Behind Method from JavaScript - Stack Overflow

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

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信