Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, January 14, 2015

WebAPI OData: Only entity types support $select and $expand

I used to get this because I was trying to return a complex type which was not an entity type and use "expand" on it so to get a child property:

builder.EntitySet<MyComplexType>("MyComplexTypes").EntityType.Collection.Action("MyAction").Returns<MyComplexType>()
[HttpPost, EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Expand)]
public IHttpActionResult MyAction(ODataActionParameters parameters)
{
 return Ok(new MyComplexType());
}

http://host/api/Entities/Default.MyAction?$expand=ChildProperty

Accessing this URL triggers:

"Only entity types support $select and $expand"

Instead of converting the type, which would have made non sens in my situation, here's what I did:

builder.EntitySet<MyComplexType>("MyComplexTypes").EntityType.Collection.Action("MyAction").Returns<string>()
[HttpPost]
public IHttpActionResult MyAction(ODataActionParameters parameters)
{
 return Json(new MyComplexType());
}

http://host/api/Entities/Default.MyAction

This returns a new MyComplexType object with all its children properties serialized.

Friday, October 31, 2014

jQuery default JSON parser for AJAX calls

By default, jQuery auto detects the response format of an AJAX request and uses a predefined list of converters to use. Here's how I set the default converter when an AJAX call returns JSON data:
$.ajaxSetup({ converters: { '* text': window.String, 'text html': true, 'text json': parseDotNetJson, 'text xml': jQuery.parseXML } }); function parseDotNetJson(data) { return JSON.parse(data, function(key, value) { if (typeof value === 'string') { var a = /\/Date\((-?\d*)\)\//.exec(value); if (a) return new Date(+a[1]); } return value; }); }
I place this code in the root of a script file. I use this to convert dates parsed to JSON by ASP.Net MVC.

More info