What is the best way to separate a string value with commas and send it to a controller?

Within my SQL table named Products, there is a field called AvailableSizes with a data type of NVARCHAR, which stores all the available sizes for a product. In my view, I have separated the values of the AvailableSizes field as shown below:

<p>
    <b>Available Sizes</b>
    @{
        var Availablesize = Model.AvailableSizes.Split(',');
    }
    @foreach (var item in Availablesize)
    {
        <div class="circleBase type2">@item</div>
    }
</p>

The above code demonstrates how I display these data values inside circles. If a user clicks on one of these circles containing the data, that value should be selected. Upon clicking the AddToCart button, the selected value should be passed to my controller action shown below:

public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl)
{
    Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
    if (product != null)
    {
        cart.AddItem(product, 1);
    }
    return RedirectToAction("Index", new { returnUrl });
 }

Below is the code behind for the Add To Cart button:

@using (Html.BeginForm("AddToCart", "Cart", new { ProductID = item.ProductID}))
{
    @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
    <input type="submit" class="btn btn-default add-to-cart" value="Add to cart" />
}

Since I am new to MVC, I would appreciate a clear solution to implement this feature. Thank you in advance.

Answer №1

To optimize your process, consider implementing an additional hidden helper to store the selected size. Use a click event on the chosen Availablesize in Jquery to update this helper. This information can then be passed to the controller's AddToCart action for further processing.

Answer №2

One way to enhance user experience is by adding a specific class when a circle is selected, and then triggering an action when the user clicks on the "add to cart" button using jQuery. The selected circle value can be retrieved and sent to the controller's action method for further processing.

Here is a code snippet demonstrating this concept:

$(document).ready(function(){
      $('.circleBase ').click(function(){
        $(this).addClass('highlight');
    })
    $('.btn').click(function(){
        var result = $('.highlight').val();
    //
    // Call your controller here
    });
});

The 'highlight' class can be used to visually distinguish the selected items.

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

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

AngularJS: Utilizing nested ng-repeats for dynamic data rendering

Currently, I am utilizing the ng-repeat directive in conjunction with the ng-repeat-start/ng-repeat-end options. Within the main loop, there is an additional inner ng-repeat. However, the problem lies in the fact that the outer ng-repeat-start declaration ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

Ext.js Ext.grid.Panel with advanced filtering capabilities

I encountered an issue with the following code snippet... Ext.define("Requestor.view.main.RequestGrid", { extend: 'Ext.grid.Panel', // Our base class. A grid panel. ... extensive code ... columns: [ ... additional code ... { ...

I attempted to initiate a transition using JavaScript, but unfortunately it failed to execute

Hey there! I'm just starting out with HTML, CSS, and JavaScript, and I've been trying to make a transition work using JavaScript. The element I'm working with is a "menu-icon" which is a span tag with a small image nested inside another div ...

Enhance the efficiency of traversing a lengthy list of comparisons within an array.filter method

I am struggling with finding an efficient method to filter out items from an array of objects based on two specific attributes matching those of the last 6 items of another array. Currently, I have a manual process in place which results in cumbersome and ...

The Angular 2 application functions perfectly when running locally, but encounters issues when running on an ec2 instance

When trying to upload an Angular 2 application to an AWS EC2 t2.small instance, it is not working as expected, even though it runs successfully in a local server. Node version: v7.0.0 NPM version: 3.10.8 There has been an EXCEPTION: Uncaught (in prom ...

The video attribute in HTML is malfunctioning on the react webpage

Currently working on setting up a basic portfolio layout with a video playing in the background on loop. However, despite making some adjustments and modifications, the video is not showing up as expected. Any insights or suggestions on what might be causi ...

Develop unique web components and distribute them across various frameworks

Currently, I am working on two projects that utilize Angular and React. I have noticed that certain components are duplicated in both projects. To streamline this process, I am considering creating a company library where I can develop custom components on ...

Adjust the package.json file for deployment

I've encountered a problem while attempting to deploy my nodejs application on Heroku. Despite following the documentation and modifying files in the root directory, I have not been successful. Below is the structure of my package.json file: { ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Displaying an Ajax progress bar during the page loading process

For my current project, I am required to implement a progress bar during the Page load event. The scenario involves receiving a request from another application, which triggers the creation of a PDF file on my page. Since this process can be time-consumi ...

Attempting to store the output of a function in a variable

My current script is designed to verify if the value of a selected element matches the span id. While the function itself functions correctly (verifying object.id via alert), I am encountering issues with variable assignment. When attempting to alert the ...

Javascript - Transforming tabular information into a hierarchical tree structure (JSON)

When extracting JSON data from a table, the format typically resembles the following simplified structure: https://i.sstatic.net/eqfXM.png The JSON format obtained might look like this: const myObjOriginal = { "rows": [{ "name": "row 1", "cell ...

Phase 2 "Loading" visual backdrop

I'm attempting to include a loading animation GIF in my Cycle 2 plugin. Is there a way to ensure that the GIF loads before the images? Right now, I have set my loading.gif as a background image. The issue is that the loading.gif isn't displaying ...

Implementing infinite scrolling with AngularJS by dynamically incorporating images from a local folder

I have attempted multiple times but continue to struggle with adding images. My goal is to create an image gallery and implement infinite scrolling using AngularJS. Is it possible to add images from a local folder rather than a database? <body ng-app=" ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Utilizing Sharepoint - accessing the Sp.Web.currentUser Property

I'm diving into a website I've been tasked to explore. While my HTML skills are limited, I'm eager to retrieve some SharePoint information using JavaScript. I launched my console and experimented with: var value = SP.Web.get_currentUser();, ...

Steps to fix the issue: Unhandled Type Error: t.addLayer is not a recognized function

I've encountered a bit of difficulty with an error that I can't seem to figure out. I'm currently working on adding a geoJSON layer to my Leaflet Map, specifically a multi-polygon representing country borders. To achieve this, I'm using ...

exceeding the maximum call stack limit when repeatedly calling a function with parameters in jQuery

I have been attempting to create a blinking icon using the following HTML code: <button type="button" id="user-card-icon-headphones" class="user-card__button" disabled="" > <i class="fa fa-headphones"></i> </button> <button t ...