I'm trying to write a basic MVC widget that will list news items with a link to each, but I'm stuck on how I can get the correct URL for each news item. Does anyone know how this is done?
I know NewsItems don't necessarily have a single link, so I'm after the URL matching the preferred page as per the News module manager. In my case I have nominated a page called "news-item" to be the default page, so all of my news URLs should have "news-item" in front of them.
How do I build this URL programmatically?
I've tried to get the full URL by running the "GetFullUrl()" method on the default page node, but I get stuck before I even get that far:
var newsItems = App.WorkWith().NewsItems().Get();
var defaultPage = newsItems.FirstOrDefault().DefaultPageId.Value;
When trying to get the ID of the default page so I can then get its corresponding URL, I immediately encounter an error:
Nullable object must have a value.
>> var defaultPage = newsItems.FirstOrDefault().DefaultPageId.Value;
Any ideas how this is supposed to work? I feel like DefaultPageId is coming back null for some reason...
You can use ContentLocationService like this:
var newsItems = App.WorkWith().NewsItems().Get();
var myNewsItem = newsItems.FirstOrDefault();
var contentLocationService = SystemManager.GetContentLocationService();
var contentLocation = contentLocationService.GetItemDefaultLocation(myNewsItem);
string defaultUrl = contentLocation == null ? "" : contentLocation.ItemAbsoluteUrl;
Hope this helps.