Please see the AJAX below:
<script type="text/javascript" src="Javascript/json2.js"></script>
<script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetData() {
$.ajax({
type: "POST",
url: "JSONExample.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: OnSuccess(),
//async: false,
failure: function (response) {
alert('there was an error counting possibles')
}
});
function OnSuccess() {
return function (response) {
alert(response);
window.location.href("JSONExample.aspx?id=" + response);
}
}
}
GetData()
</script>
and the server side code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Newtonsoft.Json;
namespace SerializeAndDeserializeJSON
{
//[Serializable]
public class Person
{
public String Name;
public int Age;
}
public partial class JSONExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((Request.QueryString["id"]== null)==false)
{
var json = Request.QueryString["id"];
var person = JsonConvert.DeserializeObject<Person>(json); //person is null
}
}
[System.Web.Services.WebMethod]
public static Person GetPerson()
{
Person p1 = new Person();
p1.Name = "Ian";
p1.Age=35;
return p1;
}
}
}
In the page load the Person object values are as follows after the page load:
Name: null Age: 0
The name should be Ian and the Age should be 35. What am I doing wrong?
-
check your response is null, change dataType to jsonBalaji Marimuthu– Balaji Marimuthu2017年01月09日 13:29:23 +00:00Commented Jan 9, 2017 at 13:29
-
Is the Json object invalid inside the OnSuccess function?Matteo Marciano - MSCP– Matteo Marciano - MSCP2017年01月09日 13:29:39 +00:00Commented Jan 9, 2017 at 13:29
1 Answer 1
What am I doing wrong?
Try setting dataType to json
instead of text
:
dataType: 'json'
And then send the javascript object as a JSON string in the id
parameter:
window.location.href("JSONExample.aspx?id=" + encodeURIComponent(JSON.stringify(response.d)));
Notice that we are using response.d
here because ASP.NET WebMethods serialize the responses using this special property.
Also you probably want to use public properties instead of fields for your model:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Some frameworks choke on fields.
6 Comments
id
parameter that you get on the server?dataType: 'json'
and then JSON.stringify(response.d)
. I have updated my answer to reflect this change. The caveat is to use response.d
.