Ajax对ASP.NET WebMethod的调用没有达到服务器端方法

时间:2015-11-30 14:26:16

标签: c# jquery asp.net ajax webforms

我试图将一个参数传递给我的代码。我到达了ajax的成功结束但是我后面的aspx.cs代码中的方法没有被调用。如果它有所作为,我会使用主文件。

使用Javascript:

$(document).ready(function () {
    var someID = "";
    $('.glyphicon-trash').click(function () {
        $.ajax({
            type: "POST",
            url: "fileName.aspx/deleteSomething",
            data: "{'deleteSomeID':'" + someID + "'}", // someID is assigned to a value by another button
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert("success"); // this alert works.
            }
        });
    });
});

fileName.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{ 
    //... stuff here
}

[WebMethod]
public static void deleteSomething(string deleteSomeID)
{
    MySqlDbUtilities db = new MySqlDbUtilities();
    MySqlCommand cmd;
    string sql = "DELETE FROM Targets WHERE targetID = @someID";
    cmd = db.GetCommand(sql);

    cmd.Parameters.AddWithValue("@someID", deleteSomeID);

    cmd.ExecuteNonQuery();
    db.Dispose();
}

" someID"单击页面上的按钮时填充。这是正常的,我三重检查。然而,该方法没有做任何事情。我也不知道它是否已经到达。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您的数据:param看起来不对我。你不需要它是一个字符串。

更新:你说你点击了成功处理程序 - 只是为了完整性你可以添加这个错误处理程序并仔细检查它是不是命中?

$(document).ready(function () {
 var someID = "";
        $('.glyphicon-trash').click(function () {
            $.ajax({
                type: "POST",
                url: "fileName.aspx/deleteSomething",
                data: { deleteSomeID: someID },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert("success"); // this alert works.
                },
                error: function (xhr, status, text) {
                  console.log(xhr.status);
                  console.log(xhr.text);
                  console.log(xhr.responseText);
                 }
            });
        });

我更习惯MVC,所以我不能保证JsonResult在webforms中工作(如果不是,我会感到惊讶)。

更改您的webmethod以返回JsonResult。

在您的代码中,将bool设置为false,并在SQL执行后将其设置为true。返回以下内容:

JsonResult returnObj = new JsonResult
        {
            Data = new
            {
                wasSuccessful = myBool,
            },
            ContentEncoding = System.Text.Encoding.UTF8,
            JsonRequestBehavior = JsonRequestBehavior.DenyGet
        };

        return Json(returnObj);

更改您的成功处理程序:

success: function (data) {
            console.log(data);
            alert(data.wasSuccessful);
        }

答案 1 :(得分:1)

请勿手动构建 def getAccountOfId(id: Long): Option[(Long, String, Option[String], Option[String])] = { DB.withConnection { implicit c => val query = """select email_address, first_name, last_name from account where id = {id};""" val rowParser = str("email_address") ~ (str("first_name") ?) ~ (str("last_name") ?) map { case emailAddress ~ firstNameOpt ~ lastNameOpt => (id, emailAddress, firstNameOpt, lastNameOpt) } SQL(query).on("id" -> id).as(rowParser.singleOpt) } } def getAccountsOfLastName(lastName: String): List[(Long, String, Option[String], String)] = { DB.withConnection { implicit c => val query = """select id, email_address, first_name from account where last_name = {lastName};""" val rowParser = long("id") ~ str("email_address") ~ (str("first_name") ?) map { case id ~ emailAddress ~ firstNameOpt => (id, emailAddress, firstNameOpt, lastName) } SQL(query).on("lastName" -> lastName).as(rowParser.*) } } 参数,而是使用data进行正确的编码:

JSON.stringify

此外,您可以处理查询可能引发异常的情况,并在UI中采取相应的操作,这是一种非常简单的方法:

$.ajax({
    type: "POST",
    url: "fileName.aspx/deleteSomething",
    data: JSON.stringify({ deleteSomeID: someID }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        alert("success");
    }
});

然后,在成功回调时管理响应:

[WebMethod]
public static string deleteSomething(string deleteSomeID)
{
    try {
        MySqlDbUtilities db = new MySqlDbUtilities();
        MySqlCommand cmd;
        string sql = "DELETE FROM Targets WHERE targetID = @someID";
        cmd = db.GetCommand(sql);

        cmd.Parameters.AddWithValue("@someID", deleteSomeID);

        cmd.ExecuteNonQuery();
        db.Dispose();
    } 
    catch (Exception e) {
        return e.Message;
    }

    return "1";
}