I have an Ajax call (for a HighChartsDB chart) in a WebForm application that calls a webservice, which uses a WebRequest to call an MVC action in another application which returns a JsonResult.
I manage to pass the data back to the ajax call but the data I get back is not parsed as a json object but just a string.
My class:
public class CategoryDataViewModel
{
public string name { get; set; }
public List<int> data { get; set; }
public double pointStart { get; set; }
public int pointInterval { get { return 86400000; } }
}
My ajax function called by the highcharts:
function getBugs(mileId) {
var results;
$.ajax({
type: 'GET',
url: 'Services/WebService.svc/GetData',
contentType: "application/json; charset=utf-8",
async: false,
data: { "mileId": parseInt(mileId) },
dataType: "json",
success: function (data) {
console.log(data);
results = data;
}
});
return results;
}
And finally my WebService
public class WebService : IWebService
{
public string GetData(int mileId)
{
string url = "http://localhost:63418/Home/GetWoWData?mileId=" + mileId;
WebRequest wr = WebRequest.Create(url);
using (var response= (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
return objText;
}
}
}
}
With this when I console.log(data) on the ajax call I get:
[{\"name\":\"Sedan\",\"data\":[30,30,30,30,35],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Low\",\"data\":[800,800,800,826,1694],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Medium\",\"data\":[180,180,180,186,317],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"High\",\"data\":[29,29,29,34,73],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Truck\",\"data\":[6,6,6,6,13],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"SUV\",\"data\":[-172,-172,-172,-179,-239],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Convertible\",\"data\":[0,0,0,0,-404],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Limo\",\"data\":[-7,-7,-7,-8,-214],\"pointStart\":1307836800000,\"pointInterval\":86400000}]
I can't seem to manage to pass back into a proper Json object. I tried converting it back to my CategoryDataViewModel with this in my webservice:
var myojb = new CategoryDataViewModel ();
using (var response = (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response .GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
}
}
return myojb;
But then I get Type 'Test.CategoryDataViewModel' is not supported for deserialization of an array.
Change:
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
to:
myojb = (List<CategoryDataViewModel> )js.Deserialize(objText, typeof(List<CategoryDataViewModel>));
and you should be fine. The array will de-serialize to a list no problem.
I've seen a similar thing before, I think you might need to change myObj to a list.
List<CategoryDataViewModel> myObjs = new List<CategoryDataViewModel>();
...
myObjs = js.Deserialize<List<CategoryDataViewModel>>(objText);
Related
Is it possible to pass 2 data types to the HttpHandler in a Webhandler
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
pathname:"~/pathname/"
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
});
The RequestPayload in the POST is [object object], is there documentation on how I can parse that object?
Hi Create a new model with all the props including the pathname prop
public class HandlerModel
{
public datatype dataprop1 {get;set;}
public datatype dataprop2 {get;set;}
public datatype dataprop3 {get;set;}
public datatype dataprop4 {get;set;}
public string pathname {get;set;}
}
then in your ashx file
public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
//set the content type, you can either return plain text, html text, or json or other type
context.Response.ContentType = "text/plain";
//deserialize the object
UserInfo objUser = Deserialize<HandlerModel>(context);
//now we print out the value, we check if it is null or not
if (objUser != null) {
context.Response.Write("Go the Objects");
} else {
context.Response.Write("Sorry something goes wrong.");
}
}
public T Deserialize<T>(HttpContext context) {
//read the json string
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
//cast to specified objectType
var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
//return the object
return obj;
}
}
having problem in, from table i get data and passed it to wcf web service
first service
public string SaveDate(string data) {
JavaScriptSerializer json = new JavaScriptSerializer();
List < string[] > mystring = json.Deserialize < List < string[] >> (data);
return "saved";
}
Second get data and ajax call
$('#btnPaymentOk').click(function () {
var objList = new Array();
$("table#tblGridProductInformation > tbody > tr").each(function () {
if ($(this).find('td.Qty').text() != '') {
objList.push(new Array($(this).find('td.LocalSalesPrice').text(), $(this).find('td.Total').text()));
//objList.push(new Array("a", "b"));
}
});
$.ajax({
type: "POST",
url: "/WebPOSService.svc/SaveDate",
data: "{data:" + JSON.stringify(objList) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
in pass look like
{data:[["1.00","1.00"],["0.60","0.60"],["0.40","0.40"]]}
json array
problem is not get data from service end
help me out
Create a DataContract:
[DataContract]
public class Data
{
[DataMember]
public List<string[]> data { get; set; }
}
Here's code I used to test it, and it worked.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ConsoleApplication
{
[DataContract]
public class Data
{
[DataMember]
public List<string[]> data { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
string jsonTxt = "{data:[[\"1.00\",\"1.00\"],[\"0.60\",\"0.60\"],[\"0.40\",\"0.40\"]]}";
var deserialized = JsonConvert.DeserializeObject<Data>(jsonTxt);
//Use this if you don't want to use DataContract, but you will have to reference Newtonsoft.Json.Linq
List<string[]> fullDeserialized = JsonConvert.DeserializeObject<List<string[]>>(JObject.Parse(jsonTxt)["data"].ToString());
}
}
}
Also, I would recommend you use Newtonsoft library for serializing/deserializing JSON data. Don't forget to add a framework reference to System.Runtime.Serializiation if you haven't already.
I am trying to post List of object (or array of object) to c# Webmethod. I am understanding how to receive as parameter in the method and convert into local List of object?.
for (var i = 0; i < usersInfo.length; i++) {
user = {
UserName : usersInfo[i].UserName,
Email : usersInfo[i].Email,
Status : status
};
users.push(user);
}
var results = "";
$('#lblError').val('');
if (users.length > 0) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserValidation.aspx/ShowResults',
data: "{'UsersInfo':'" + JSON.stringify(users) + "'}",
async: false,
success: function (data) {
results = data.d;
$('#lblError').val(results);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
}
});
}
Code behind
[WebMethod]
public static void ShowResults(//Here how receive list object from javascript)
{
//convert parameter to List<UsersInfo>
}
public partial class UsersInfo
{
public string UserName { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
Try to replace this line
data: JSON.stringify({ UsersInfo: users}),
James you are the right track; you need to define the correct type for the ShowResults parameter so that the binding will work and bind the incoming json to your UsersInfo class.
Your UsersInfo class appears to be a simple POCO so should bind without any custom binding logic :
[WebMethod]
public static void ShowResults(List<UsersInfo> UsersInfo)
{
//No need to convert
}
I've been using a hard coded JSON object:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
I'm then iterating this object calling the items by index and using .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
Now I want to pull this data from the server so I created an object to handle the properties and have this action method:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
I'm calling it with this AJAX:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
Now my results object contains:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.
Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like
$.each(data, function(i, obj) {
alert(obj.name);
});
but this returns undefined. Any help would be great.
public JsonResult TestAjax(int leagueId)
{
var results = new List<BaseballViewModel>()
{
new BaseballViewModel{ DivisionId = 1},
new BaseballViewModel{ DivisionId = 2}
}.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/TestAjax",
type: "GET",
data: { leagueId: 5 },
success: function (data) {
// alert(JSON.stringify(data)); show entire object in JSON format
$.each(data, function (i, obj) {
alert(obj.DivisionId);
});
}
});
Instead of:
$.each(data, function(i, obj) {
alert(obj.name);
});
why don't you try:
$.each(data.results, function(i, obj) {
alert(obj.name);
});
If you create a Model class that way :
[Serializable()]
public class MyResponse
{
public int Id {get; set;}
public string Code {get; set;}
}
And that you create a list of "MyResponse"
You will just have to do
return Json(new { data = listOfMyResponse}, JsonRequestBehavior.AllowGet);
I have a problem, I cannot add custom objects to my List. However, if I add some predefined objects (strings, integers..) my code works just fine.
This is my class which is always returned on all ajax calls to this controller, it contains boolean Status and List of objects.
public class returnData
{
public bool status { get; set; }
public List<object> data { get; set; }
}
This is the class for the object I want to add to this list:
public class file
{
public string ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
The code where I use this:
returnData data = new returnData();
...
DriveFile file = JsonConvert.DeserializeObject<DriveFile>(Json);
file f = new file();
if (file.mimeType == "application/vnd.google-apps.folder")
{
f.Type = "folder";
f.ID = file.id;
f.Name = file.title;
data.data.Add(f);
}
The error I get has no useful info, as this code compiles and the error is in Chrome Console log when the ajax is executed.
Image of google chrome console
However, when I use this line of code
data.data.add("some string");
my function will work flawlessly and return Object which contains boolean Status and List of objects (strings, integers..)
So back to my question, how do I add my objects to this list?
EDIT: There are no server side errors, the code compiles and runs just fine, so this probably is some jquery/ajax error.
This is the ajax code for my debugger:
86 $.ajax({
87 url: $('#url').val(),
88 type: $('#type option:selected').val(),
89 contentType: "application/json; charset=utf-8",
90 dataType: "json",
91 data: $('#data').val(),
92 success: function (result){
93 console.log(result)
94 },
95 error: function (err){
96 console.log(err)
97 }
98 });
Here is the complete method, but the method seems to be OK, it is the ajax or something to do with jquery I guess.
[OperationContract]
public returnData listChildren(string folderId)
{
returnData data = new returnData();
List<object> myList= new List<object>();
bool status = true;
try
{
string Json = Response("https://www.googleapis.com/drive/v2/files/" + folderId + "/children", "GET");
//get the children list
if (!Json.Contains("error"))
{
DriveChildlist list = JsonConvert.DeserializeObject<DriveChildlist>(Json);
foreach (DriveChildren child in list.items)
{
string uriString = child.childLink;
//get the info for each child in the list
Json = Response(uriString, "GET");
if (!Json.Contains("error"))
{
DriveFile file = JsonConvert.DeserializeObject<DriveFile>(Json);
file f = new file();
if (file.mimeType == "application/vnd.google-apps.folder")
{
f.Type = "folder";
f.ID = file.id;
f.Name = file.title;
data.data.Add(f);
}
else if (file.mimeType == "application/myMimeType")
{
f.Type = "file";
f.ID = file.id;
f.Name = file.title;
data.data.Add(f);
}
}
else
{
status = false;
}
}
}
else
{
status = false;
}
}
catch(Exception)
{
status = false;
}
data.status = status;
if (!status)
{
data.data = null;
//data.data is null if status is false
}
return data;
}
As written your C# code won't work but will compile. It will throw an error when the ajax is called and you may never see the error message (depending on how your system is setup).
Here is correct code (given your snippet)
returnData data = new returnData();
data.data = new List<object>();
// rest of your code.
I have solved this using the Newtonsoft.Json. I have serialized the object using this code:
string jsondata = JsonConvert.SerializeObject(data);
and then I returned the serialized string instead of object. Looks like visual studio development center failed to serialize my object, even after adding [Serializable()] to my class. Any info on that?