Find category guid programmatically

Posted by Community Admin on 04-Aug-2018 11:02

Find category guid programmatically

All Replies

Posted by Community Admin on 29-Aug-2011 00:00

Hello. I would like to find the guid of a category or tag programmatically. Currently I am getting it manually from the database and hard-coding it into my user controls, but this is a bad practice that I'd like to avoid.

Here is the code that I am using at the moment. It does not generate any errors, but it returns null:

TaxonomyManager manager = TaxonomyManager.GetManager();
 
 var tax1 = manager.GetTaxonomies<HierarchicalTaxonomy>().Where(t => t.Name == "myCategory").SingleOrDefault();
 var tax2 = manager.GetTaxonomies<FlatTaxonomy>().Where(t => t.Name == "myTag").SingleOrDefault();
 
 Guid id1 = tax1.Id;
 Guid id2 = tax2.Id;

Thanks.

Posted by Community Admin on 29-Aug-2011 00:00

Hi Joao,

The reason why the result is null is that by invoking GetTaxonomies, you are actually trying to get the Taxonomy, but not the taxonomy item. By calling GetTaxonomies, you will be able to get "Tags" or "Categories" or any custom Taxonomy that you have. You may perceive this as the name of the classification, but not the classification items.

Back to the question, if you want to get the Taxa (the Taxonomy items/classification items), you should use GetTaxa method. In this case, your example would look like this:

TaxonomyManager manager = TaxonomyManager.GetManager();
  
 var tax1 = manager.GetTaxa<HierarchicalTaxonomy>().Where(t => t.Name == "myCategory").SingleOrDefault();
 var tax2 = manager.GetTaxa<FlatTaxonomy>().Where(t => t.Name == "myTag").SingleOrDefault();
  
 Guid id1 = tax1.Id;
 Guid id2 = tax2.Id;

If you get null result, this means that the item you query for doesn't exists, or the query is incorrect (usually the filters applied to the query are wrong). More information on Taxonomies and Taxa can be found here - http://www.sitefinity.com/40/help/developers-guide/sitefinity-essentials-taxonomies.html

I hope this helps. Let us know if we can be of further help.

Kind regards,
Georgi
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

This thread is closed