Search code examples
c#umbraco

Umbraco - Get Content from text instead of nodeId


I currently have the following code in my project:

var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
IPublishedContent currentContent = umbracoHelper.TypedContent(UmbracoContext.Current.PageId);
var contentService = UmbracoContext.Current.Application.Services.ContentService;

int configPageId = 0;

if(currentContent.AncestorsOrSelf().Select(x => x.Id).ToArray().Contains(1309))
{
    configPageId = 1872;
} 
else if(currentContent.AncestorsOrSelf().Select(x => x.Id).ToArray().Contains(1308))
{
    configPageId = 1660;
}
if(configPageId != 0)
{
    IContent content = contentService.GetById(configPageId);
    linkCreditSimulator = content.GetValue("linkCreditSimulator").ToString();
    linkAskNow = content.GetValue("linkAskNow").ToString();
}

I think whoever did this, was due to different environments having different ids.

I was hoping to normalize this.

If I run the following query:

    SELECT TOP (1000)  d.text
  FROM [cmsContent] c
  LEFT join cmsContentXml cxml on c.nodeId = cxml.nodeId
  LEFT join cmsMedia m on m.nodeId = c.nodeId
  LEFT join cmsDocument d on d.nodeId = c.nodeId
  LEFT join cmsMedia cm on cm.nodeId = c.nodeId
  LEFT join cmsMember mb on mb.nodeId = c.nodeId
  LEFT join cmsPreviewXml p on p.nodeId = c.nodeId
  LEFT join cmsTagRelationship tr on tr.nodeId = c.nodeId
  where c.nodeId = 1872

I get the value "Simulator", which is the same across environments.

I was trying to find any method in the contentService similar to

IContent content = contentService.GetByName("Simulator");

But I was unable. Do you know if there's a way to achieve this? What other approach would you recommend?

Best Regards


Solution

  • Assuming the "configPage" is a specific content type, you can query for that type using its alias: https://our.umbraco.com/documentation/Reference/Querying/UmbracoHelper/#contentatxpathstring-xpath - that way you only have to hardcode the alias and not a bunch of IDs that, as you say, can and will differentiate between environments.

    Use of ContentService should also be kept to a minimum as it uses database access (like that huge SQL query in your example) instead of the cache. ContentAtXPath uses the cache.