简体   繁体   中英

Passing json object using AJAX error in code behind

I have created an HTML file that will try to pass a json value to my asp page but I get an error on my asp. My HTML works ok and passing values {'a':'a','b':'b'}, but the asp page were not able to use the value.

  1. Here is my HTML code and showing the JSON value {'a':'a','b':'b'}:

      <html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btnAdd').click(function() { var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "','" + $('#t2').val() + "' : '" + $('#p2').val() + "'}"; $.ajax({ type: 'POST', url: 'http://localhost/Base_Data/InsertItem.aspx', contentType: 'application/json; charset=utf-8', data: json_obj, dataType: 'json', success: function(msg) { alert('Success!'); }, error: function(msg) { alert('Error!'); } }); }); }); </script> </head> <body> <div> Type: 1: <input type="text" id="t1" /> Property 1: <input type="text" id="p1" /> Type 2: <input type="text" id="t2" /> Property 2: <input type="text" id="p2" /> <input type="button" id="btnAdd" value="Add object!" /> </div> </body> </html> 
  2. Here is my ASP page code behind:

     public class Test { public Test(string json) { var serializer = new JavaScriptSerializer(); var result = serializer.DeserializeObject(json); var first = int.Parse(result["t1"]); var second = int.Parse(result["t2"]); } public string first { get; set; } public string second { get; set; } } 

Any replies will be highly appreciated. Thanks in advance!

When passing data to the $.ajax method, the data parameter is generally a javascript object with key/value pairs and those key/value pairs are put into a query string as in foo=bar&person=ted . Putting a JSON string in there and then trying to parse that JSON in your server is the hard way to send a couple values to your server and it's a lot more work to parse it on the server too.

Using the built in data capabilities of the $.ajax method will put the data into query string format and your server can automatically parse that out too - all without writing any new code on client or server.

From the jQuery docs :

data

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

I would avoid generating pure JSON manually as it can always lead to problems, try using something like JSON.stringify which will make your data construction easier as you can use proper JS objects eg

var jsonObj = { t1: $('#t1').val(), p1: $('#p1').val(), t2: $('#t2').val(), p2: $('#p2').val() };

$.ajax({  
    type: 'POST',  
    url: 'http://localhost/Base_Data/InsertItem.aspx',  
    contentType: 'application/json; charset=utf-8',  
    data: JSON.stringify(jsonObj),  
    dataType: 'json',  
    success: function(msg) {  
        alert('Success!');  
    },  
    error: function(msg) {  
        alert('Error!');  
    }  
}); 

Then on the server side deserialize your json into a dynamic object and get the data back out:

public Test(string json)  
{  
    var serializer = new JavaScriptSerializer();  
    var result = serializer.Deserialize<dynamic>(json);  

    var first = int.Parse(result["t1"]);  
    var second = int.Parse(result["t2"]);   
}

Update

Based on your comment you won't be able to use a dynamic object, you should be able to deserialize your JSON into a Dictionary eg

var result = serializer.Deserialize<Dictionary<string, string>>(json);

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