问题
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).
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 Stackoverflow.
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();
}
}
}
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.
回答1:
Before connecting to Database, you want to make sure WebMethod is working.
Here is the working example - client sends user object and server returns it back.
ASPX
<%@ 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>
Code Behind
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; }
}
}
来源:https://stackoverflow.com/questions/41507343/asp-net-call-webmethod-via-ajax-not-working