Copied to clipboard

Flag this post as spam?

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


  • Josh Bula 13 posts 75 karma points
    Apr 22, 2014 @ 17:51
    Josh Bula
    0

    Web API Get Documents by Document Type

    This query works in a MacroPartial but how can I return the same data in Web API?

    var query = CurrentPage.AncestorOrSelf(1).DescendantsOrSelf().Where("Visible && DocumentTypeAlias == @0", "newsItem").OrderBy("createDate desc");
    

    This doesn't work because obviously CurrentPage doesn't exist in the current context...

    public IEnumerable<IPublishedContent> GetNews()
    {
        return CurrentPage.AncestorOrSelf(1).DescendantsOrSelf().Where("Visible && DocumentTypeAlias == @0", "newsItem").OrderBy("createDate desc");
    }
    

    Can you please point me to a working example of how to return documents or nodes through Web API, or tell me how to modify the above to make it work? Thanks!

  • Josh Bula 13 posts 75 karma points
    Apr 22, 2014 @ 20:29
    Josh Bula
    0

    After much trial-and-error and frustration over the lack of documentation, this how I ended up getting it to work...

    public class NewsItem
    {
        public string Headline { get; set; }
        public string Body { get; set; }
        public DateTime CreateDate { get; set; }
    }
    public class NewsApiController : UmbracoApiController
    {
        public List<NewsItem> GetNews()
        {
            var newsItems = new List<NewsItem>();
            var items = Umbraco.ContentAtXPath("//newsItem").Where("Visible").OrderBy("createDate desc");
            foreach (var item in items)
            {
                var newsItem = new NewsItem();
                newsItem.Headline = item.GetPropertyValue("newsItemHeadline").ToString();
                newsItem.Body = item.GetPropertyValue("newsItemBody").ToString();
                newsItem.CreateDate = Convert.ToDateTime(item.CreateDate);
                newsItems.Add(newsItem);
            }
            return newsItems;
        }
    
    }
    

    If there are any better or easier ways to accomplish this, please let me know.

Please Sign in or register to post replies

Write your reply to:

Draft