简体   繁体   English

如何从JavaScript调用方法背后的代码

[英]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 尝试调用C#方法

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

But I could not found any solution that work.... 但是我找不到任何可行的解决方案。

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: 为了使其正常工作,请确保在url设置的方法位置正确,并且该方法是publicstatic ,并且已添加[WebMethod]属性,例如:

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

if the url is "/Default.aspx/ServerSideMethod" then your method should look like this: 如果url是“ /Default.aspx/ServerSideMethod”,则您的方法应如下所示:

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

Try this in js: 在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: 在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(). 在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", . 我的意思是在url: "/Default.aspx/ServerSideMethod",是否有指向您服务器的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. 我以为您正在执行ajax调用,但是您根本没有启动服务器,或者没有侦听器将此URL链接到您的方法。

If you want to call a non static method from ajax, I suggest you to create a web service and call it from javascript. 如果要从ajax调用非静态方法,建议您创建一个Web服务并从javascript调用它。 You can have non static methods inside a web service. 您可以在Web服务中使用非静态方法。

There are quite a lot of examples in Stackoverflow on how to call a web service from javascript. Stackoverflow中有很多关于如何从javascript调用Web服务的示例。 Call ASP.NET web service method from JavaScript 从JavaScript调用ASP.NET Web服务方法

asp.net Markup asp.net标记

<!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. 和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 可能是这个技巧完全为您服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM