Documentation

Ucommerce includes full API reference documentation and lots of helpful articles to help you build your e-commerce site as effortlessly as possible.

Topics Payment Providers
v7.18

Building Category Navigation

When building a webshop the most essential part is for your visitors to browse categories with products. In this article we'll explain how to retrieve categories very easily.

Using CatalogLibrary

You can use the CatalogLibrary located in the namespace

    using Ucommerce.Api;
    using Ucommerce.Infrastructure;
    using Ucommerce.Search.Slugs;

To get hold of CatalogLibrary you can inject it into your controller, or you can resolve it using ObjectFactory:

    
    var catalogLibrary = Ucommerce.Infrastructure.ObjectFactory.Instance.Resolve<Ucommerce.Api.ICatalogLibrary>();
    
    

Once you have CatalogLibrary you can get the categories you're interested in based on how you want to display them. Please be mindful the amount of data you have. All queries are paged and will only per default return you the first 300 in your result set.

Getting the first level of categories can be done like this:

    var rootCategories = catalogLibrary.GetRootCategories();
    
    

The code above will use the catalog in context in case no catalog guid is specified in the optional parameter.

Rendering subcategories once you start navigating your category structure can be done like shown below.

    
    var currentCategory = catalogLibrary.GetCategory();
    
    var categories = catalogLibrary.GetCategories(new List<Guid>() {currentCategory.Guid});
    
    

In a category navigation / structure it is important to be able to link to the category you're displaying. This can be done like this:

    var catalogContext = Ucommerce.Infrastructure.ObjectFactory.Instance.Resolve<Ucommerce.Api.ICatalogContext>();
    var urlService = Ucommerce.Infrastructure.ObjectFactory.Instance.Resolve<Ucommerce.Search.Slugs.IUrlService>();
    
    urlService.GetUrl(catalogContext.CurrentCatalog, new []{ category });
    
    

Custom query for categories

In case you want to access the lower level APIs and do custom queries against the category index like shown below.

    var categoryIndex = ObjectFactory.Instance.Resolve<Ucommerce.Search.IIndex<Ucommerce.Search.Models.Category>>();
    
    

For a complete reference on how you can use IIndex to query the indexes please read here.

Sample using MVC

    
    
    public class CategoryNavigationController : Controller
    {
        private readonly ICatalogLibrary _catalogLibrary;
        private readonly IUrlService _urlService;
        private readonly ICatalogContext _catalogContext;
    
        public CategoryNavigationController()
        {
            _catalogLibrary = ObjectFactory.Instance.Resolve<ICatalogLibrary>();
            _urlService = ObjectFactory.Instance.Resolve<IUrlService>();
            _catalogContext = ObjectFactory.Instance.Resolve<ICatalogContext>();
        }
        
        public ActionResult CategoryNavigation()
        {
            var categoryNavigationModel = new CategoryNavigationViewModel();
    
            IEnumerable<Category> rootCategories = _catalogLibrary.GetRootCategories().ToList();
    
            categoryNavigationModel.Categories = MapCategories(rootCategories);
    
            return View(categoryNavigationModel);
        }
        
        private IList<CategoryViewModel> MapCategories(IEnumerable<Category> categoriesToMap)
        {
            var categoriesToReturn = new List<CategoryViewModel>();
    
            var allSubCategoryIds = categoriesToMap.SelectMany(cat => cat.Categories).Distinct().ToList();
            var subCategoriesById = _catalogLibrary.GetCategories(allSubCategoryIds).ToDictionary(cat => cat.Guid);
    
            foreach (var category in categoriesToMap)
            {
                var categoryViewModel = new CategoryViewModel
                {
                    Name = category.DisplayName,
                    Url = _urlService.GetUrl(_catalogContext.CurrentCatalog,
                        _catalogContext.CurrentCategories.Union(new[] { category }))
                };
                categoryViewModel.Categories = category.Categories
                    .Where(id => subCategoriesById.ContainsKey(id))
                    .Select(id => subCategoriesById[id])
                    .Select(cat => new CategoryViewModel
                    {
                        Name = cat.DisplayName,
                        Url = _urlService.GetUrl(_catalogContext.CurrentCatalog, new[] { category, cat })
                    })
                    .ToList();
    
                categoriesToReturn.Add(categoryViewModel);
            }
    
            return categoriesToReturn;
        }
    }
    
    

Sample using Web API

    [System.Web.Http.RoutePrefix("myRoutePrefix")]
    public class AvenueClothingApiBasketController : ApiController
    {
        private ICatalogLibrary _catalogLibrary;
    
        public AvenueClothingApiBasketController()
        {
            _catalogLibrary = ObjectFactory.Instance.Resolve<ICatalogLibrary>();
        }
    
        [System.Web.Http.Route("GetCategories")]
        public IHttpActionResult GetCategories(Guid? catalogGuid,Guid? categoryGuid, uint skip = 0, uint take = 300)
     
        {
            if (categoryGuid.HasValue)
            {
                return Json(_catalogLibrary.GetCategories(new List<Guid>() {categoryGuid.Value}, skip, take));
            }
    
            return Json(_catalogLibrary.GetRootCategories(catalogGuid, skip, take));
        }
    }