Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Andrew Gibson 16 posts 106 karma points
    4 days ago
    Andrew Gibson
    0

    Api Controller return JSON results

    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.)

  • Alex Skrypnyk 3980 posts 14114 karma points mvp
    4 days ago
    Alex Skrypnyk
    0

    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

  • Andrew Gibson 16 posts 106 karma points
    4 days ago
    Andrew Gibson
    0

    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:

        [HttpGet]
        public JsonResult<IEnumerable<Event>> EventsForDate(DateTime date)
        {
            //return new[] { "Cuthbert", "Dribble", "Grub", date.ToLongDateString() };
            var rootNodes = Umbraco.TypedContentAtRoot();
            var eventsNode = rootNodes.FirstOrDefault(x => x.DocumentTypeAlias == "eventsList");
    
            var events = eventsNode.Children.OfType<Event>()
                .Where(x => x.Date == date);
            //.Where(x => x.IsVisible()); ?!
    
    
            //return Json<IEnumerable<Event>>(events.ToList());
            return Json(events);
        }
    

    Assuming I have an Enumerable of EventsViewModel what should the return type be, and how do I return the collection? Thanks again.

  • Alex Skrypnyk 3980 posts 14114 karma points mvp
    4 days ago
    Alex Skrypnyk
    101

    This code will return json or xml - depends on requested client, so if client asks for json - response will be json:

        [HttpGet]
        public IEnumerable<Event> EventsForDate(DateTime date)
        {
            //return new[] { "Cuthbert", "Dribble", "Grub", date.ToLongDateString() };
            var rootNodes = Umbraco.TypedContentAtRoot();
            var eventsNode = rootNodes.FirstOrDefault(x => x.DocumentTypeAlias == "eventsList");
    
            var events = eventsNode.Children.OfType<Event>()
                .Where(x => x.Date == date);
            //.Where(x => x.IsVisible()); ?!
    
    
            //return Json<IEnumerable<Event>>(events.ToList());
            return events;
        }
    

    If you want to return json in browsers windows for example, add this code to "ApplicationStarted" event:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                                  "text/html",
                                  StringComparison.InvariantCultureIgnoreCase,
                                  true,
                                  "application/json"));
    

    Thanks,

    Alex

  • Andrew Gibson 16 posts 106 karma points
    4 days ago
    Andrew Gibson
    0

    Thank you!

        [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...?

  • Andrew Gibson 16 posts 106 karma points
    4 days ago
    Andrew Gibson
    0

    Sorted the last niggling question, I just needed the Umbraco.Web namespace to check IsVisible():

     using Umbraco.Web;
    
    .Where(x => x.Date == date && x.IsVisible())
    
  • Alex Skrypnyk 3980 posts 14114 karma points mvp
    4 days ago
    Alex Skrypnyk
    0

    Just wanted to add :) Gald that you solved the issue!

Please Sign in or register to post replies

Write your reply to:

Draft