I Have an asp.net mvc api controller method that has a List as its return method. When called it returns this json data:
[
{
"AreaName": null,
"AreaId": 0,
"DestinationName": "Alanya",
"DestinationId": 14,
"CountryName": "Tyrkiet",
"CountryId": 15
},
{
"AreaName": null,
"AreaId": 0,
"DestinationName": "Antalya",
"DestinationId": 113,
"CountryName": "Tyrkiet",
"CountryId": 15
}
]
Earlier when I had this method in an asp.net mvc it would look similar to this:
earlier json data:
{
"ContentEncoding":{
"IsSingleByte":true,
"BodyName":"iso-8859-1",
"EncodingName":"Western European (Windows)",
"HeaderName":"Windows-1252",
"WebName":"Windows- 1252",
"WindowsCodePage":1252,
"IsBrowserDisplay":true,
"IsBrowserSave":true,
"IsMailNewsDisplay":true,
"IsMailNewsSave":true,
"EncoderFallback":{
"MaxCharCount":1
},
"DecoderFallback":{
"MaxCharCount":1
},
"IsReadOnly":true,
"CodePage":1252
},
"ContentType":"application/json;",
"Data":
and then the above list would be added inside of the Data wrapper
My question is - how do I get this "wrapper" format back when using the asp.net mvc web api ?
Your JSON is a normal format for list of objects and the second one, older represents an object. So when you need it - just return object.
Probably, in the older version (normal mvc) you did return something like this:
return JsonResult(new { Data = myList });
now, in WebApi, you do this:
return myList;
That explains why the old result has all that formatting around. To get back the old wrapper in your WebApi, I guess you would simply do something like this:
return new { Data = myList };
If the above does not work, try the following:
Change the return type of your method to HttpResponseMessage
use this:
return Request.CreateResponse(HttpStatusCode.OK, new { Data = myList });
I don't have anything to debug at the moment but both of the above should work. If they don't, it is probably because the serialization-deserialization does not like anonymous objects (this may give you more problems with XML than JSON actually).
Anyway, in my opinion it is a lot easier to live with the new version of your object, mainly because it does NOT have a (noisy) wrapper around :)
You can create your own returning type, something like this:
public class InvoiceResult
{
public int numberResultTotal;
public int numberResultPaged;
public List<InvoiceDTO> results;
}
ASP.NET Web API will convert it to JSON, XML or any other format and your client will get something like this:
<InvoiceResult>
<numberResultPaged>20</numberResultPaged>
<numberResultTotal>999999</numberResultTotal>
<results>
<InvoiceDTO>
<ID>110</ID>
<Active>2</Active>
<Date>01/01/2010</Date>
</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
</results>
</InvoiceResult>
Related
var allCategories = _db.Categories;
var result = from c in allCategories
select new[] { c.CategoryID, c.Name, c.SortOrder};
when i use select new {...}; but i get result as object array.
But when i try to use select new[] {...}; i get the following error.
No best type found for implicitly-typed array
Below is my complete Method of Controller.
public ActionResult Index(jQueryDataTableParamModel param=null)
{
if (Request.IsAjaxRequest() && param!=null)
{
var allCategories = _db.Categories;
var result = from c in allCategories
select new[] { c.CategoryID, c.Name, c.SortOrder};
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allCategories.Count(),
iTotalDisplayRecords = allCategories.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
return View();
}
If i am doing wrong way please guide me to right path as i am new to ASP.NET MVC.
Update:
I am getting JSON Array like this:
{"sEcho":"1","iTotalRecords":3,"iTotalDisplayRecords":3,"aaData":[{"CategoryID":1,"Name":"Computers","SortOrder":1},{"CategoryID":2,"Name":"Laptops","SortOrder":1},{"CategoryID":3,"Name":"Mobiles","SortOrder":1}]}
where as i want Json Array like this
{"sEcho":"1","iTotalRecords":3,"iTotalDisplayRecords":3,"aaData":[["CategoryID":1,"Name":"Computers","SortOrder":1],["CategoryID":2,"Name":"Laptops","SortOrder":1],["CategoryID":3,"Name":"Mobiles","SortOrder":1]]}
The reason behind this is datatables is not showing data in grid, so i guess this is the reason behind not showing data. As i am getting the array like the second one in PHP and datatables works fine over there.
Update: 2
I Just Tried like this,
select new [] { Convert.ToString(c.CategoryID), c.Name, Convert.ToString(c.SortOrder)};
as everything will become string. but now after this error is gone i am not getting the error relating to converting of string.
LINQ to Entities does not recognize the method 'System.String
ToString(Int32)' method, and this method cannot be translated into a
store expression.
What you want is not valid JSON. You could create it using string concatenation, but it would not be possible to parse it as JSON.
If you want to produce something that is possible to parse as JSON you need to follow the syntax rules.
If you want a collection of keys and values, you use an object:
{"CategoryID":1,"Name":"Computers","SortOrder":1}
If you use an array you only have values, no keys:
[1,"Computers",1]
Ok. After many tries i finally got the result somehow in arrays rather then in objects.
Many Thanks to #Guffa Also as He helped Alot in Fixing my Problem.
He Finally gave the reply
new object[] { c.CategoryID.ToString(), c.Name, c.SortOrder.ToString() }
Which should have solved my problem but for some reason asp.net LINQ is not supporting .ToString() functions and i did got this error.
The array type 'System.Object[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List1[System.Object]' instead.
I am not good in ASP.NET MVC specially with Databases and C# so i start back to googeling.
I think i had to call query two times.
first result is converted ToList() ToList i think supports the ToString Function.
var categories = (from category in allCategories
select category).ToList();
Then here when returning Json i wrote the query back again but here i used the Categories from First Query and then .ToString was working.
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allCategories.Count(),
iTotalDisplayRecords = allCategories.Count(),
aaData = (from category in categories
select new [] {category.CategoryID.ToString(), category.Name, category.SortOrder.ToString()}).ToArray()
},
It gave me the result i wanted but i am not sure if this is the right way. What should be the Professional way or good way to have a secure and quick response controller. As i don't want to make a mess of my Code.
A newbie question.
Just started on asp.net web api project that going well getting and posting plain object.
But how doe I Get and Post object with child objects. The same as Order with order items.
Who cab help me with a simple example without advance features as OData etc.
Thanks in advance
Anders Pedersen
Create your object graph and return it so that web API can serialize it for you. So, you will create an Order object like this and return it.
public Order Get(int id)
{
var order = new Order() { Id = id };
order.OrderItems.Add(new OrderItem() { ProductName = "Cool Item", Price = 12.34 };
order.OrderItems.Add(new OrderItem() { ProductName = "Cool Item", Price = 12.34 };
return order;
}
If you now look at the JSON or XML payload of this GET response, that is what you will need to post to get the binding work with your POST action method.
public HttpResponseMessage Post(Order order) { ... }
I'm doing my first steps with Newtonsoft Json parser, but there are very fex examples on VB.net apperently. I just want to parse a string, and then I want to be able to loop throught the different list
This is my code :
Dim JSON As String
Dim values As Newtonsoft.Json.Linq.JObject
JSON = "{'mailadresses': { 'List1':{'Stefaan Somers': 'JoskeVermeulen#gmail.com', 'Markske': 'mdtre#gmail.com' }, 'List2':{'Stefaan XSomers': 'Test#gmail.com', 'xMarkske': 'mdrmdtre#gmail.com' }}"
values = JObject.Parse(JSON)
It directly gives me the error when running :
Unexpected end of content while loading JObject. Path 'mailadresses', line 1, position 221.
Any idea also on how to loop through the different elements. I don't want to cast to a custom class, as described in many samples
Your json isnt valid according to jsonlint.
try this instead:
{
"mailadresses": {
"List1": {
"StefaanSomers": "JoskeVermeulen#gmail.com",
"Markske": "mdtre#gmail.com"
},
"List2": {
"StefaanXSomers": "Test#gmail.com",
"xMarkske": "mdrmdtre#gmail.com"
}
}
}
I use Page-/WebMethods for handling actuallisize data every x seconds.
Normaly I have 1 Object created on my won, which I get back with 3 informations: time / name / price.
Now I build a site with x members of my object is needed, so:
can I easily get a List<> of my own object back to JavaScript
how can I access specific rows, I mean, how I know that the time of row 1 in my list is for time of 1 in the site?
Return the result as JSON string and then parse that in client side.
I do not think, JavaScript would be able to detect if its a List<>. JSON is the way to send and receive data via PageMethods in ASP.NET Ajax. Did you check this link which uses array to send and receive data, http://forums.asp.net/p/1222967/2198696.aspx#2198696.
Okay... ahm... it's nothing special to get Lists back over JavaScript... I only make a funny syntax error.
So if someone is interessted:
<script type="text/javascript" language="javascript">
function UpdateAll()
{
setTimeout("UpdateAll()", 99990);
PageMethods.Update(OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
alert(result.detailsList[0].Preis);
}
[WebMethod(EnableSession = true)]
public static object Update()
{
Business.AuctionInformationDetails details = new Business.AuctionInformationDetails();
List<Business.AuctionInformationDetails> detailsList = new List<Business.AuctionInformationDetails>(); ;
//Fill list
return new
{
detailsList = detailsList
};
}
(AuctionInformationDetails are only an object with 3 string).
I am using the JSON2 script in an asp page to parse JSON post data.
After parsing the data, I have an object in VBScript that allows for notations such as:
jsonData.key
I wish to parse through all the keys, however, I have no knowledge of the key names.
How would I go about doing this?
Example JSON:
{ "dbtable":"TABLE1", "dbcommand": "INSERT", "dbfilter": "ID" }
Thanks
You need to enumerate the property names of the object however this is a very alien thing to do in VBScript. You will need to build some other Jscript functions to assist converting the object into something more easily consumed in VBScript.
If the data is really as simplistic as the example in the question then you could use this function:-
function toDictionary(o)
{
var result = Server.CreateObject("Scripting.Dictionary");
for (var key in o)
result.Add(key, o[key]);
return result;
}
Now in VBScript:-
Dim myData: Set myData = toDictionary(jsonData);
For Each Key In myData
'' // Each Key is a property for jsonData
Next