在Ajax WebMethod中生成json字符串并将其发送回aspx

时间:2014-12-09 17:36:05

标签: c# jquery asp.net ajax

我正在尝试在Ajax WebMethod中生成一个json字符串,并将其发送回aspx成功结果并打印出结果。 json2字符串不正确。有什么建议?

Default.aspx.cs

    [System.Web.Services.WebMethod]
    public static string GetJSONdata(string id)
    {
        string json2 = "";
        string val = "1;2;3;4;5";
        string[] arr = val.Split(';');
        string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
        string cmdStr = "SELECT ([datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
        try
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@idd", id);
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if (rdr.Read())
                        {
                            arr[1] = rdr[1].ToString();
                            arr[2] = rdr[2].ToString();
                            arr[3] = rdr[3].ToString();
                            arr[4] = rdr[4].ToString();
                        }
                    }
                    conn.Close();
                    cmd.Dispose();
                    conn.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        json2 = "{'datajson' : [{'id' : '" + id + "', 'datetime' : '" + arr[1] + "', 'col1' : '" + arr[2] + "', 'col2' : '" + arr[3] + "', 'col3' : '" + arr[4] + "'}]}";
        return json2;
    }

Default.aspx的

<script type="text/javascript" src="~/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%= Button1.ClientID %>").click(function () {
            var id = $("#<%= TextBox1.ClientID %>").val();
            var data = { ID:id };
            var json1 = JSON.stringify(data);
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetJSONdata",
                data: json1,
                dataType: "json",
                success: function (result) {
                    $("#<%= TextBox2.ClientID %>").val(result.datajson[0].id);
                    $("#<%= TextBox3.ClientID %>").val(result.datajson[0].datetime);
                    $("#<%= TextBox4.ClientID %>").val(result.datajson[0].col1);
                    $("#<%= TextBox5.ClientID %>").val(result.datajson[0].col2);
                    $("#<%= TextBox6.ClientID %>").val(result.datajson[0].col3);
                },
                error: function (Msg) {
                    $("#<%= Label1.ClientID %>").text('failed:' + Msg.status +  '    response:' + Msg.responseText);

                }
            }); return false;
        });
    });

错误代码:

failed:500 response:{"Message":"Invalid web service call, missing value for parameter: \u0027id\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
 at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
 at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
 at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

2 个答案:

答案 0 :(得分:1)

  1. 帖子键必须匹配
  2. 不要将数据字符串化
  3. 使用库来构建JSON不要手动执行(参见@joe comment)
  4. <强> AJAX:

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetJSONdata",
        data: {clientId : id },
        success: function (result) {...},
        error: function (Msg) {...}
    });
    

    <强> C#:

    [System.Web.Services.WebMethod]
    public static string GetJSONdata(string clientId){...}
    

    构建JSON:

    使用库,JSON.NET是一个很好的库。它的工作方式,你创建一个模型:

    public class Datajson
    {
        public string id { get; set; }
        public string datetime { get; set; }
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
    }
    

    然后用它来构建你的字符串

    List<Datajson> data = new List<Datajson>();
    Datajson json = new Datajson();
    json.id = clientId;
    json.datetime = rdr[1].ToString();
    json.col1 = rdr[2].ToString();
    json.col2 = rdr[3].ToString();
    json.col3 = rdr[4].ToString();
    data.add(json);
    
    var jsonString = JsonConvert.SerializeObject(data);
    

    然后记录下来查看。

答案 1 :(得分:0)

只是一个猜测...
但是当你在ajax请求中发送“ID”时,你在GetJSONdata中期待“id”。可能希望保持两者一致