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

时间:2013-11-01 12:44:32

标签: c# javascript asp.net webforms

我有几天阅读并搜索这个问题的答案,但我没有找到。

我正在使用此代码

$('#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;
        });
        });

尝试调用C#方法

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

但我找不到任何有效的解决方案......

5 个答案:

答案 0 :(得分:3)

要使其正常工作,请确保url中设置的方法位置正确且方法为publicstatic且添加了[WebMethod]属性如:

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

如果url是“/Default.aspx/ServerSideMethod”,那么您的方法应如下所示:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

首先,我建议你写一些调试语句。在doAll()的第一行写一些输出。它实际上会让您知道您是否真的将请求从​​浏览器发送到您的服务器。我的意思是如果url: "/Default.aspx/ServerSideMethod",上有任何指向您服务器的链接。我在想你正在进行ajax调用,但你根本没有启动服务器,或者没有将这个URL链接到你的方法的监听器。

答案 3 :(得分:0)

如果你想从ajax调用非静态方法,我建议你创建一个 web服务并从javascript调用它。您可以在Web服务中使用非静态方法。

Stackoverflow中有很多关于如何从javascript调用Web服务的例子。 Call ASP.NET web service method from JavaScript

答案 4 :(得分:-1)

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>

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


    }
}

可能是这个伎俩帮助你完整

相关问题