简体   繁体   中英

Generate a json string in a Ajax WebMethod and send it back to the aspx

I am trying to generate a json string in a Ajax WebMethod and send it back to the aspx success result and printout the results. The json2 string is not correct. Any suggestions?

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;
        });
    });

Error code:

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"}
  1. The post keys must match
  2. Don't stringify the data
  3. Use a library to build JSON don't do it manually (see @joe comment)

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){...}

Building JSON:

Use a library , JSON.NET is a good one. The way it works, you create a model:

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; }
}

Then use it to build your string

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);

then log it to see.

Just a guess...
But you're expecting "id" in GetJSONdata while you're sending "ID" in ajax request. Might want to keep both of them consistent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM