通过Ajax的ASP.NET调用webMethod无法正常工作

问题描述:

我一直在为一个学校项目工作,我想在该项目中通过客户端调用服务器方法(C#方法).我发现使用jQuery是执行此操作的更好方法之一(由于ajax).我使它工作了,但是一周或更长时间后,它突然停止工作了.除了名称之外,我认为我对方法没有太多更改.但我似乎无法弄清楚问题所在. (我使用调试来检查该方法是否被调用,并且似乎没有被调用).

I've been working on a project for school and I within that project I want to call a server method (C# method) via the client side. I found out that using jQuery is one of the better methods to do this (because of ajax). And I got it working but after a week or more it suddenly stopped working. I don't think I changed much to the method, except the name. But I can't seem to figure out the problem. (I used debugging to check whether the method gets called or not and it doesn't seem to be calling).

我通过Ajax调用WebMethod的代码:

The code I have for calling the WebMethod via Ajax:

function callDatabase() {
    $.ajax({
        type: 'POST',
        url: 'Index.aspx/setGridData',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert(msg);
        }
    });
}

我在*上找到了这段代码.

I found that piece of code here on *.

然后我将其用作我的方法:

Then I use this as my method:

[WebMethod]
    public static void setGridData() {
        string data = "Test";

        if (HttpContext.Current.Session["UserID"] != null) {
            MySqlCommand command = new MySqlCommand("UPDATE userdata SET griddata = ? WHERE userid = ?;");
            command.Parameters.Add(new MySqlParameter("griddata", data));
            command.Parameters.Add(new MySqlParameter("userid", HttpContext.Current.Session["UserID"].ToString()));
            MySqlDataReader reader = Global.SqlConnection.executeSQLCommand(command);

            if (reader.RecordsAffected <= 0) {
                reader.Close();
                command = new MySqlCommand("INSERT INTO userdata(userid, griddata) VALUES (?, ?);");
                command.Parameters.Add(new MySqlParameter("userid", HttpContext.Current.Session["UserID"].ToString()));
                command.Parameters.Add(new MySqlParameter("griddata", data));
                reader = Global.SqlConnection.executeSQLCommand(command);

                reader.Close();
            } else {
                reader.Close();

            }
        }
    }

如果有帮助,则jQuery位于名为"JavaScript"的文件夹中,而WebMethod位于该文件夹之外.

The jQuery is in a folder called "JavaScript" and the WebMethod is outside the folder, if this helps.

我希望有人可以帮助我.

I hope someone could help me with this.

在连接数据库之前,您要确保WebMethod正常运行.

Before connecting to Database, you want to make sure WebMethod is working.

这是工作示例-客户端发送 user 对象,服务器将其返回.

Here is the working example - client sends user object and server returns it back.

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="DemoWebApplication.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <button type="button" onclick="postData();">Post Data</button>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
        </script>
        <script type="text/javascript">
            function postData() {
                var user = { firstName: "John", lastName: "Doe" };
                $.ajax({
                    type: "POST",
                    url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
                    data: "{user:" + JSON.stringify(user) + "}",
                    contentType: "application/json",
                    success: function (msg) {
                        console.log(msg.d);
                    }
                });
            }
        </script>
    </form>
</body>
</html>

隐藏代码

using System.Web.Script.Serialization;

namespace DemoWebApplication
{
    public partial class Default : System.Web.UI.Page
    {
        [System.Web.Services.WebMethod]
        public static string PostJson(User user)
        {
            user.FirstName += "Test";
            user.LastName += "Test";
            return new JavaScriptSerializer().Serialize(user);
        }
    }

    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}