Find Category

3 weeks ago
Hello,

Is there a function how I can get the ID of the currently displayed category?

Best regarde
3 weeks ago
admin side or front side?
if you want current display category in front side, just simple you get id in component


@await Component.InvokeAsync(typeof(WidgetViewComponent), new { widgetZone = PublicWidgetZones.CategoryDetailsBeforeProductList, additionalData = Model })
@{
    var catalogProductsViewData = new ViewDataDictionary(ViewData);
    catalogProductsViewData["fetchUrl"] = Html.Raw(Url.Action("GetCategoryProducts", "Catalog", new { categoryId = Model.Id }));
}

This code was added to the CategoryTemplate.ProductsInGridOrLines.cshtml page and contains components for displaying products based on the current category.
3 weeks ago
alshrouf wrote:
Hello,

Is there a function how I can get the ID of the currently displayed category?

Best regarde


Hi
In which section do you want to get the category ID?
1. The homepage has categories coming from the HomepageCategoriesViewComponent.
2. The categories are also displayed on the left column on the columns section on the catalog pages if enabled.
3. Category detail page. Category details and sub-category sections are available here.


First, you can check if the Model available on these pages has the ID property for the category. If yes, then you can use it directly.

If not, then need to do some customization to make the ID available,
  a. You can either extend the model and bind the ID in the modelfactory while preparing the model for the sections
  b. Or You can also get the category ID from the category URL slug(generally URL slug is available on all of the sections where the category is available). You can create a simple method to get the category ID from the slug and use it. Something like this



public async Task<int?> GetCategoryIdByUrlSlug(string slug)
{
    // find record by the URL slug
    var urlRecord = await _urlRecordService.GetBySlugAsync(slug);
    if (urlRecord==null || urlRecord.EntityName!=nameof(Category))
        return null;
    return urlRecord.EntityId;
}