Reputation: 3374
This is my first time using AJAX with ASP.NET so please allow m some rope.
I have a simple AJAX request that I wish to retuen a JSON string but ASP.NET keeps formatting the JSON string as XML
here is my code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetModels()
{
string response;
using (var context = new myDataModel())
{
var m = from model in context.ListModels select model;
var serializer = new JavaScriptSerializer();
response = serializer.Serialize(m);
}
return response;
}
this is called but returns an XML node containing my JSON string really confused
Upvotes: 1
Views: 1186
Reputation: 2344
This is my method for returning JSON from a webservice using ASP.NET
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetJSON()
{
DataTable dtMarkers = new DataTable();
dtMarkers.Load(<<STORED PROCEDURE>>.GetReader());
string[][] myArray = new string[dtMarkers.Rows.Count][];
int i = 0;
foreach (DataRow marker in dtMarkers.Rows)
{
myArray[i] = new string[] { marker["ID"].ToString(), marker["Title"].ToString(), marker["Blurb"].ToString(), marker["Url"].ToString(), marker["LongLatPoint"].ToString() };
i++;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(myArray);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Flush();
Context.Response.Write(strJSON);
}
this particular example reads Googlemaps pointers from a database and returns them to the ASP.NET page for displaying on an instance of Google Maps.
Upvotes: 3
Reputation: 2943
Try to define it like:
public JsonResult GetModels()
{
//.........
return new JsonResult() { Data = new { result=response } };
}
Upvotes: 0