Choose products and showcase them on a single screen. Send the findings back to the controller

As a newcomer to MVC and still learning Javascript, I understand that my code may not be perfect. Currently, I am working on creating a view where users can select items from a dropdown list and have them dynamically displayed below a button called btnAdd. I believe that JavaScript is the way to go for this functionality. Once users have made their selections, they can click on the btnCheckout button to return their choices to the controller. Here is what I have so far, but I could use some guidance!

View:

@model OnlineTakeout.Models.ProductView

@{
     Layout = null;
}

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <script src="~/Scripts/jquery-2.1.0.min.js"></script>
     <title>Index</title>
</head>
<body>
 @using (Html.BeginForm()){
<div>
    Pick Product:
    <br />
        @Html.DropDownListFor(m=>m.ProductId, Model.Products) 
    <br />
    <p>
        <input type="button" value="AddToOrder" id="btnAdd" />    
    </p>
</div>
    }
<div>
 @using (Html.BeginForm()) {    

    //Added Items would display here after individual btnAdd button presses  

    <p>
        <input type="button" value="CheckOut" id="btnChkOut" />    
   </p>

 }
</div>

</body>
 <script>
    $(function () {
        $("#btnAdd").click(addProduct);
    })

    $(function () {
        $("#btnChkOut").click(saveProducts);
    })

    var productList = [];
    var id = $("#ProductId").val();

    // This function would also display these items on view
    function addProduct() {
        productList.push(id);
    };


    function saveProducts() {
        $.post("/Product/Index/" + productList());
    }

    }
</script>

Controller:

public class ProductController : Controller
{
    //
    // GET: /Product/

    public ActionResult Index()
    {
        var model = new ProductView();
        var products = new List<Product> { new Product { ProductId = 1, Name = "Product One", Price = 1.00m },  
            { new Product { ProductId = 2, Name = "Product Two", Price = 2.00m } }};
        model.Products = new SelectList(products, "ProductId", "Name");

        return View(model);
    }

    [HttpPost]
    public JsonResult Index(int[] prodList)
    {

        return Json("Index");
    }

Answer №1

My preferred method for accomplishing this task involves utilizing jQuery.

To achieve this, you must establish an event handler in jQuery that responds to the change event of your dropdown list. This event should trigger a call to an action within your controller, which will bind a partial controller and return the corresponding partial view. It is crucial that the return type be ActionResult, as this will deliver the HTML content back to the success method of your post. Finally, embed the returned HTML onto the page to complete the process.

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

Error encountered: TypeError: __webpack_require__.t is not a function - Issue appears only on live server, while localhost runs without any problem

I set up an e-commerce site that runs smoothly on localhost. However, when I deploy it to a live server, an error appears. Interestingly, the error disappears after reloading the page. Here is the code snippet: import React, { useEffect, useState } from & ...

Having difficulty initializing the WCF service host

I'm attempting to set up a service host for my WCF application. Upon launching the app, I encounter an error message: The service cannot be started. This service has no endpoint defined. Please add at least one endpoint for the service in config ...

Obtain a collection of strings from a list of JSON objects

I need help extracting a list of strings from the following JSON data: "example":{[ {"@name":"name1"}, {"@name":"name2"}, {"@name":"name3"}, {"@name":"name4"} ]} My goal is to retrieve the values of @name. I have been trying to accomplish this using jayw ...

Is it possible to expand a class and modify or conceal its members while still adhering to the Open/Closed Principle in C

Is it possible to inherit from a parent class and exclude certain members in the child class without violating the open/closed SOLID principle? I am exploring a solution like the one below, but I am concerned about potential exceptions when using reflectio ...

Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure. For example, our routes are structured like this: /:local ...

Speed up replacement of "variables" in HTML code with JavaScript

I am in the process of creating a dynamic single page website with multiple languages using javascript and the innovative html template-tag. I want to utilize custom variables such as {{txt.welcome}} in my html files that will be substituted with the appro ...

Exploring an object to find the value of an array

Here is the object that I am working with: var list = { nums: [ [117], [108] ], numsset: [ [2256, 2265], [234], [3445, 3442] ] }; Imagine there is an input field on the page where a user can type a number. How can I search the ...

Having difficulty displaying all the database values in my ListView widget

I need help with displaying all the values from my localhost database in a ListView. The REST process and background tasks are handled by my AsyncTask, so I cannot use the onCreate method for this purpose. Here is the relevant code snippet: public class ...

Converting a button from non-favorite to favorite in Angular: Step-by-step guide

How can I change the state of a button that is inside * NgFor when consuming an API? The issue arises when I try to toggle the favorite status from one to another, as it changes all buttons instead of just the one clicked. Is there a way to maintain the st ...

The unavailability of passed-in values during the runtime of a function within an Angular application

It's becoming clear to me that there is a piece of the puzzle missing when it comes to understanding exactly when certain function outputs are available in JavaScript. In my Angular application, I am trying to extract a user's initials by extrac ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

Creating a copy of a div using jQuery's Clone method

I need help figuring out how to clone a div without copying its value. I've attempted various methods, but they all seem to include the value in the cloned element. This is the jQuery function I am currently using: $('#add_more').click(fu ...

What is the best way to transform api.Response into a data frame or json format using Python?

Looking at the data I have, my goal is to transform it into a data frame. t = cmc.globalmetrics_quotes_latest() (Cmc refers to the coinmarketcap api) type(t)= coinmarketcapapi.response """ RESPONSE: 820ms OK: {'active_cryptocurrencies ...

All-in-one package containing NestJS, Typescript, Webpack, and all necessary node_modules

Is there a way to package a NestJS project with node_modules for offline use in an application? webpack.config.js const path = require('path'); module.exports = { entry: path.join(__dirname, 'dist/main.js'), target: 'node&ap ...

Adjusting the width of a <div> element dynamically using two array variables within a Vue.js loop

As a beginner in vuejs, I am facing a challenge in understanding its functionality. Currently, I have implemented a 'vuejs for each-loop' within a div to fetch data from a JSON object. My goal is to calculate the current distance relative to a m ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

Is it possible that following or unfollowing a user through Ajax can result in the href attribute of other links changing? Check out the

Attempting to clarify a peculiar situation with as much detail as possible. Attached are images/examples. A specific page is dedicated to displaying all the users a particular user follows. users_controller.rb def following @pals = current_user.followi ...

The functionality in axios similar to uploading a file with curl is the --

I am currently working on uploading a gif to Gfycat through their public API. To do this, I have been using the cURL command line with: curl https://filedrop.gfycat.com --upload-file /tmp/name In an attempt to convert this process to Node.js using axios ...

When utilizing Angular, the JSON response might show the message "Script execution refused"

Whenever I attempt to retrieve data from my WordPress wp-json using a filter, I encounter the following error message: Refused to execute script from '....' because its MIME type ('application/json') is not executable, and strict MIME t ...