for each item, assign a unique ink color

Hello there! Currently, I am working on a straightforward online shopping MVC application. Within this application, there is a table containing three categories: Laptops, Mobiles, and Consoles. I have created a partial view that fetches these categories from the database and displays them in a list, with each category name inside a button.

Partial View: _Categories

@model OnlineShopping.MyViewModel

<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
    <div class="btn-group mr-2" role="group" aria-label="First group">

        @foreach (Category item in Model.CategoriesV)
        {
            <button type="button" class="btn btn-secondary"> 
                @item.CategoriesName 
            </button>
        }
    </div>
</div>

To display this partial view on the index page, I use the following code:

Index.cshtml

<div class="catmenu" style="display: none;">
    @Html.Partial("_Categories", Model)
</div><br />

In addition, there is another table in the database called Products, which contains the product names and their corresponding category IDs from the category table.

For example:

Category table:

CategoryID = 1

CategoryName = Mobiles

Product table:

ProductID = 1

ProductName = Apple

CategoryID = 1

My goal is to create a functionality where clicking on a specific category button (e.g. laptops, consoles, mobiles) would redirect to the respective partial view showing all products with the same category ID. For instance, clicking on the laptops button would display all laptop products, while clicking on the consoles button would show products such as Xbox and PS, as they share the same category ID for consoles.

I hope my explanation was clear enough. Thank you for your assistance!

Answer №1

To start off, I suggest assigning a unique ID to the button in the initial loop. I recommend using the ID column for this purpose. Here's how you can do it:

@model OnlineShopping.MyViewModel

<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
    <div class="btn-group mr-2" role="group" aria-label="First group">

        @foreach (Category item in Model.CategoriesV)
        {
            <button type="button" class="btn btn-secondary catclick" id="item.Category_Id"> 
                @item.CategoriesName 
            </button>
        }
    </div>
</div>

In the controller, I will implement a method that fetches items based on their category:

public ActionResult GetCatItems(int id){
  // logic to retrieve data here
  return View("_mypartialview",partialdata)

}

This method will return a rendered HTML with the data you need for your view. All you have to do is insert this generated HTML in the right place:

$.ajax({
// ajax call to fetch data
success(data){
  // when successful, clear the parent container of your partial view
   $('.catmenu').html('');


 //load the returned HTML into the view
  $('.catmenu').html(data);
}

Since we returned the view in the controller and fetched it using an AJAX call, you now have the HTML of that partial view with the populated data:

return View("_partial",data);

After a successful AJAX call, your partial view will be rendered in the designated container:

//when successful, clear the parent container of your partial view
   $('.catmenu').html('');


 //load the returned HTML into the view
  $('.catmenu').html(data);

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

Changing the content of a DOM element containing nested elements using JavaScript/jQuery

Need some help with a DOM element that looks like this: <span>text</span> <b>some more text</b> even more text here <div>maybe some text here</div> How can I replace text with candy to achieve this result: <span> ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

"Effortlessly Arrange Multiple Gridview Rows Using Checkbox Selection in jQuery Drag and Drop

Struggling with getting checkboxes clicked when a GridViewRow becomes selected. Utilizing jQuery Methods like .sortable and .selectable. Worked as intended but looking to have a checkmark placed on the checkbox cbBulkSort within the GridView's first c ...

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

Ensuring thread safety by locking a shared variable in parallel threads using C#

I am currently working on a code snippet that involves a BlockingCollection in C#. var queue = new BlockingCollection<int>(); queue.Add(0); var producers = Enumerable.Range(1, 3) .Select(_ => Ta ...

Real-life application of ASP.Net web stress testing tool

Tools like WCAT, httperf, and openload are useful for simulating static load on a server. However, I require a tool that can accurately test the actual load of an ASP.Net solution. This means that when testing with 1k simultaneous users, each user should ...

Bcrypt.compare failing to match the passwords

I implemented a bcrypt.compare function in my code, but I'm running into an issue where it seems to not be comparing the passwords correctly. Regardless of the input password, the function always returns a status of ok. Can someone take a look at the ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

Enhancing Embedded Lists Within Mongodb

Seeking help with the mongodb syntax to update a specific item within a document's list. Take this sample document for instance. Let's say I need to modify the StartTime for id 524725e61788d8078c900afb { "_id": { "$oid": "524725e61788d8078c9 ...

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

Creating a pair of linked dropdown menus in ReactJS that open simultaneously

Having two dropdown menus can be a bit cumbersome, especially when you have functions dedicated to opening each one individually. It would be more efficient to combine them into one function for simplicity. If anyone has a solution for this, I would greatl ...

Querying in SQL using LINQ

I need assistance converting a SQL Query into LINQ format for C# .NET 3.5 select distinct location, country from Customer where Customer_Code ='1001'; The SQL Query is working fine, but I am encountering an error when trying to use the LINQ q ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

A neutral-toned backdrop that briefly shows up for a quick 7-second interlude during a background-image

Recently I created a website. On this website, there is a feature where 3 images change every 7 seconds for a total of 3 cycles. The code snippet used for this functionality is as follows: var swap; function run(interval, frames) { var int = 1; ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

What is the best way to create a function that triggers another function every minute?

Currently, I have a function that checks if a user is authenticated: isAuthenticated = (): boolean => { xxx }; I am working with AngularJS and I want to create a new function called keepCheckingAuthentication() This new function should call the ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

After submitting the form, I must only deactivate the checkbox that has been selected

Here is the HTML code I am working with: I have multiple checkboxes designed as buttons to select a room, but it's quite annoying when they all get selected at once. $("form").submit(function() { $('.seat input:checkbox').prop("disable ...

Execute the function when the element comes into view

Is there a way to create a function that will automatically attach itself to an element when it comes into view? I have multiple elements on my page - element1, element2, and element3. Instead of using a large if statement, I would like to write a functio ...