Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c# - 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

question from:https://stackoverflow.com/questions/65870306/umbraco-get-content-from-text-instead-of-nodeid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...