将jquery数据传递给WebMethod

时间:2012-01-07 08:43:00

标签: jquery asp.net webmethod

我知道我们已经有很多关于这个主题的帖子,但我无法弄清楚如何将数据传递给WebMethod!我只需要将一个字符串数据传递给我的WebMethod,但是我是否需要使用列表数据类型?

的.js

function buttonClicked () {
$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "Chat.aspx/send",
    data: "{'text':'" + $("#writeBox").val() +  "'}",
    success: function () {
    },
    error: function () {
    }
});
}

.aspx(使用完整代码更新)//我注释掉了导致错误的部分

[System.Web.Services.WebMethod]
void send (string text) {
    string id = HttpContext.Current.Request.Cookies["id"].ToString();
    string queryString = "INSERT INTO Log (ID, Text, Date) Values (" + id + ", " + text + ", GETDATE())";
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=ChatV1;Integrated Security=True");
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(queryString, con);
    using (con)
    {
       con.Open();
       //cmd.ExecuteNonQuery();
    }
}

1 个答案:

答案 0 :(得分:2)

[System.Web.Services.WebMethod]
public static void send (string text) {
    string id = HttpContext.Current.Request.Cookies["id"].ToString();
    string queryString = "INSERT INTO Log (ID, Text, Date) Values (" + id + ", " + text + ", GETDATE())";
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=ChatV1;Integrated Security=True");
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(queryString, con);        
       con.Open();
       cmd.ExecuteNonQuery();
       con.Close();
}