I have my Api controller working and returning a string array:
[Route("api/[controller]")]
public class EventsController : UmbracoApiController
{
[HttpGet]
public IEnumerable<string> EventsForDate(DateTime date)
{
return new[] { "Cuthbert", "Dribble", "Grub", date.ToLongDateString() };
}
}
I will now search the Umbraco content for relevant event details. What return type do I use to return this data as JSON, and what method to convert a list of Umbraco nodes to JSON, please?
(With ASP.NET Core I would just use IActionResult.)
I think it's better to create a new class for returning the data that you need, Umbraco nodes contain too many data for transferring via api to client browser I think.
Create a simple class with needed fields, fill objects and return them.
[HttpGet]
public JsonResult<IEnumerable<EventViewModel>> EventsForDate(DateTime date)
{
var rootNodes = Umbraco.TypedContentAtRoot();
var eventsNode = rootNodes.FirstOrDefault(x => x.DocumentTypeAlias == "eventsList");
var events = eventsNode.Children
.OfType<Event>()
.Where(x => x.Date == date)
.Select(x => new EventViewModel { Title = x.Title.ToString(), Location = x.Location, Date = x.Date });
//.Where(x => x.IsVisible()); ?!
//return Json<IEnumerable<Event>>(events.ToList());
return Json(events.Any() ? events : null);
}
A remaining minor/niggling question is how can I incorporate the check for IsVisible as this isn't available for IPublishedContent, Event or EventViewModel...?
Api Controller return JSON results
I have my Api controller working and returning a string array:
I will now search the Umbraco content for relevant event details. What return type do I use to return this data as JSON, and what method to convert a list of Umbraco nodes to JSON, please?
(With ASP.NET Core I would just use IActionResult.)
Hi Andrew
I think it's better to create a new class for returning the data that you need, Umbraco nodes contain too many data for transferring via api to client browser I think.
Create a simple class with needed fields, fill objects and return them.
Thanks,
Alex
Hello and thank you.
That makes sense. I'll create a ViewModel and map my Events data.
I'm still struggling with the return type though, the following is failing:
Assuming I have an Enumerable of EventsViewModel what should the return type be, and how do I return the collection? Thanks again.
This code will return json or xml - depends on requested client, so if client asks for json - response will be json:
If you want to return json in browsers windows for example, add this code to "ApplicationStarted" event:
Thanks,
Alex
Thank you!
A remaining minor/niggling question is how can I incorporate the check for IsVisible as this isn't available for IPublishedContent, Event or EventViewModel...?
Sorted the last niggling question, I just needed the Umbraco.Web namespace to check IsVisible():
Just wanted to add :) Gald that you solved the issue!
is working on a reply...