Implement isotope filter on product page details using ASP.NET Core MVC

While working on my .Net core project, I implemented an isotope filter dynamically. Everything seemed to be functioning correctly, however, a minor error occurred. When selecting a specific category, the position of the product did not appear as expected. Please refer to the images linked below:

View All Products

After applying the filter, the image did not change its position (it should have appeared first)

Here's a snippet of my code from Index.cshtml:

@model BornoMala.Models.ViewModels.ProductDetailsVM
<section id="portfolio" class="portfolio">
    <div class="container">
        <div class="row" data-aos="fade-up">
            <div class="col-lg-12 d-flex justify-content-center">
                <ul id="portfolio-flters">
                    <li data-filter="all" class="filter-active filter-button">All</li>
                    @foreach (var obj in Model.Categories)
                    {
                        <li class="filter-button" data-filter="@obj.Name.Replace(' ','_')">@obj.Name</li>
                    }
                </ul>
            </div>
        </div>

        <div class="row portfolio-container" data-aos="fade-up">
            @foreach (var prod in Model.Products)
            {
                <div class="col-lg-4 col-md-6 portfolio-item  filter @Model.Category.Name.Replace(' ','_')">
                   <div class="portfolio-img"><img src="@Model.ImageUrl" class="img-fluid" alt=""></div>
                    <div class="portfolio-info">
                    <h4>@Model.Title</h4>
                    <p>By <b>@Model.Title</b></p>
                    </div>
                  </div>
            }
        </div>

    </div>
</section>

In the Isotope.js section of my code:

$(window).on('load', function () {
        var portfolioIsotope = $('.portfolio-container').isotope({
            itemSelector: '.portfolio-item',
        });
});

 $(document).ready(function () {

            $(".filter-button").click(function () {
                $("#portfolio-flters li").removeClass('filter-active');
                $(this).addClass('filter-active');

                var value = $(this).attr('data-filter');
                if (value == "all") {
                    $('.portfolio-item').show('3000');
                }
                else {
                    $(".portfolio-item").not('.' + value).hide('2000');
                    $('.portfolio-item').filter('.' + value).show('2000');

                }
            });

    });

I encountered an issue where if I remove the ".portfolio-container" class from the "load window" in the Isotope.js script, the details page container loses flexibility. Feel free to check out another image showcasing this problem:

Image card displaying lack of flexibility

Answer №1

Here are a couple of methods you can try:

1. Modify the window onload section to:

$('.portfolio-container').isotope({
        itemSelector: '.element-item'
    });

This will display the first option, but there may be a delay in loading in my demonstration. https://i.sstatic.net/xg0GB.gif

2. Alternative approach using isotope:

Note the data-filter content within 'portfolio-filters', it may differ from yours. The idea behind this method is to invoke isotope every time you click on a different filter button

(with a different data-filter).

Modified code:

Be aware of

data-filter="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="597719363b33771738343c770b3c2935383a3c">[email protected]</a>(' ','_')">@obj.Name</li>
Data stored in database

is Digital, however you can add '.' before '@', so it can be identified by isotope.

<div class="container">
<div class="row" data-aos="fade-up">
    <div class="col-lg-12 d-flex justify-content-center">
        <ul id="portfolio-flters">
            <li data-filter="*" class="filter-active filter-button">All</li>
            @foreach (var obj in Model.Categories)
            {
                <li class="filter-button" data-filter="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f9d7b9969b93d7b798949cd7ab9c8995989a9c">[email protected]</a>(' ','_')">@obj.Name</li>
            }
        </ul>
    </div>
</div>
<div class="row portfolio-container" data-aos="fade-up">
    @foreach (var product in Model.Products)
    {
        <partial name="_IndividualProductCard" model="product" />
    }
</div>
@section Scripts
{
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>
<script>
    $mygrid = $('.portfolio-container').isotope({
        itemSelector: '.portfolio-item'
    });

    $('#portfolio-flters').on('click', 'li', function () {
        var filterValue = $(this).attr('data-filter');
        $mygrid.isotope({ filter: filterValue });
    });
</script>
}

Data in database:

https://i.sstatic.net/7YBYu.png https://i.sstatic.net/q0saj.png

Result:

https://i.sstatic.net/qwYOl.gif

Answer №2

@Tisa I've implemented your code as instructed Index.cshtml

<section  class="portfolio">
    <div class="container">
        <div class="row" data-aos="fade-up">
            <div class="col-lg-12 d-flex justify-content-center">
                <ul id="portfolio-flters">
                    <li data-filter="*" class="filter-active filter-button">All</li>
                    @foreach (var obj in Model.Categories)
                    {
                        <li class="filter-button" data-filter="@obj.Name.Replace(' 
                        ','_')">@obj.Name</li>

                    }

                </ul>
            </div>
        </div>
        <div class="row portfolio-container" data-aos="fade-up">
            @foreach (var product in Model.Products)
            {
                <partial name="_IndividualProductCard" model="product" />
            }

        </div>

    </div>
</section>

_IndividualProductCard.cshtml

@model BornoMala.Models.Product
<div class="col-lg-4 col-md-6 portfolio-item  filter @Model.Category.Name.Replace(' ','_')">
    <div class="portfolio-img ">
        <img src="@Model.ImageUrl" width="100" height="50" />
    </div>
</div>
 @section Scripts
    {
        <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
        <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>
        <script>
            $mygrid = $('.portfolio-container').isotope({
                itemSelector: '.portfolio-item'
            });

            $('#portfolio-flters').on('click', 'li', function () {
                var filterValue = $(this).attr('data-filter');
                $mygrid.isotope({ filter: filterValue });
            });
        </script>
    }

product model

namespace project.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Description { get; set; }

        [Required]
        public string Artist { get; set; }

        [Required]
        [Range(1,1000)]
        public double Price { get; set; }

        public string ImageUrl { get; set; }

        [Required]
        public int CategoryId { get; set; }

        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

        [Required]
        public int StyleId { get; set; }

        [ForeignKey("StyleId")]
        public Style Style { get; set; }
    }
}

productdetailsVM

namespace project.Models.ViewModels
{
    public class ProductDetailsVM
    {
        public IEnumerable<Product> Products { get; set; }
        public IEnumerable<Category> Categories { get; set; }
        
    }
}

All category images are displaying except for others where no image is shown. Blank image link

I have resolved the filtering issue using jQuery, but the problem with the image position remains due to not calling '"$mygrid"'. How can this be resolved?

@section Scripts{

    <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
    <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>
   <script>
            $mygrid = $('.portfolio-container').isotope({
                itemSelector: '.portfolio-item'
            });

            $(".filter-button").click(function(){

                var value = $(this).attr('data-filter');
                if(value == "all")
                 {
                   $('.filter').show('0010');
                 }
            else
                  {
                    $(".filter").not('.'+value).hide('0010');
                    $('.filter').filter('.'+value).show('0010');

               }
            });
   </script>
        

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a variable within the ng-repeat loop

I need help figuring out how to incorporate my variables into ng-repeat, as shown in the examples below. controller.js $scope.firstParams = $stateParams.firstId; template.html <span style="margin-left:3px;" ng-repeat="list in user.userlists.{{firstP ...

Updating the icon of an action column dynamically in Ext JS4

Using the getClass function to display icons in the action column: { xtype: 'actioncolumn', id:'actionColumnGridUsers', width: 30, hideable: false, items: ['->', { getClass: function (v, meta, rec) { ...

Click on any checkbox to select all checkboxes at once

I have created a table with each column containing a checkbox. My goal is to select all checkboxes in the table when I click on the checkbox in the top row (th). Can someone guide me on how to achieve this? Below is my code: <table style="width:100%"& ...

Transform a legitimate web address into an acceptable file path

I find myself in a situation that has me scratching my head. Imagine I want to convert any valid URL into a valid pathname for use on an image proxy with a URL structure like this: http://image-proxy/hash_of_url/encoded_url Is there an efficient way to a ...

Remove a file from a directory using AJAX in an ASP.NET C# application

I've been attempting to remove a file from a folder using AJAX and Handler.ashx. I have a link that, when clicked, calls the removeFile() method which then invokes a method in handler.ashx to delete the file. However, the process is not functioning as ...

Managing relationships between tables in Entity Framework Core 2 through foreign key constraints

I am currently working on a model that involves two references to another model. After looking into this issue, I found solutions that were related to older versions of .Net Core. Here is the model: public class Match { public int ID { get; set; } ...

Guide to cycling through Promise results and populating a form

I have an asynchronous function that returns a Fetch Request: async fetchDataByCodOS(codOS){ const res = await fetch( 'http://localhost:5000/cods/'+codOS, { method:"GET" } ).then(res => ...

Utilizing HTML5 to automatically refresh the page upon a change in geolocation

I have a web application built with AngularJS. One of the functionalities is activated only when the user is in close proximity to specific locations. To make this work, I can constantly refresh the page every 5 seconds and carry out calculations to dete ...

Is there a way to save HTML form data to a CSV file within a designated directory?

Does anyone know how to save a CSV file to a specific folder using JavaScript? I have an HTML form and I want to save the data as a CSV file in a particular directory. I've tried the code below but it's not working. <form onSubmit="WriteToFi ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Developing a dynamic table using data retrieved from an API within a JS React Bootstrap framework

I'm new to JavaScript and struggling with a problem. I am trying to create a dynamic table displaying information about cars using data from an API provided by a friend (full JSON shown at the end of the post). While I can successfully fetch and displ ...

Utilizing the Facebook Like Button with ASP.NET MVC in C#

I have recently developed a website showcasing various products, with the intention of displaying product details when users click on each item. I am looking to integrate the Facebook Like Button into these product pages. After consulting http://developer ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

Calling a function after a value has been updated

Does anyone have any suggestions for how to create a Logout button that unsets sessions and then closes the current tab? I've been able to destroy the sessions, but I'm struggling with closing the tab. I've tried using setInterval and echoin ...

Creating a Cloudinary Angular URL: A Step-by-Step Guide

Currently, I am utilizing Cloudinart on Angular and my goal is to create a Cloudinary URL. <cl-image public-id="public_id"> <cl-transformation height="270" width="480" crop="fill"/> & ...

Tips for resolving the issue of "Validation procedure indicates that the remote certificate is invalid"

Attempting to send emails via Mailkit has presented a challenge due to an error message stating "System.Security.Authentication.AuthenticationException" with the message "The remote certificate is invalid according to the validation procedure" (translated ...

DiscordjsError: The client attempted to use a token that was not accessible

Hey there, I'm currently working on implementing a bot for my server and encountered an issue while attempting to create a member counter for voice channels. After completing the setup, I ran node index.js in the terminal, only to receive an error ind ...

What makes the ng-file-upload Upload service so special?

Why do I need to use the Upload service with ng-file-upload in this specific way? Upload.upload({ url: '/postMyFormHere', data: { fileToUpload: model.file, someField1: model.field1, someField2: model.field2, ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

Encountering Axios CanceledError while attempting to forward a POST request using Axios

While attempting to relay a POST request from an express backend to another backend using axios, I encountered an axios error stating "CanceledError: Request stream has been aborted". Interestingly, this issue does not arise when dealing with GET requests. ...