Building an efficient shopping cart feature on a website with asp.net mvc4, incorporating the use of html5 local

After receiving suggestions on my previous question, I delved into further research and began the coding process.

The flowchart I am currently following is as follows:
I have a products page and a partial view for the Cart.

====> When a user clicks "add to cart," the product details are sent to an ASP Controller where a model instance is created for a cart object.
====> The Model Object is then sent to an AngularJS controller using JSON.
====> I store the data in local storage and display it in the ASP Cart partial view.
====> Updating changes in quantity and calculating totals is easily done using Angular.

However, I am facing difficulty in passing the model object from the ASP Controller to the Angular Controller and displaying it in the partial view.

=================================================================================

Here are snippets of the code that I have written:

JavaScript for sending product data from Products Page to ASP Controller:

function HandleAddtoCartButton() {
$(document).on("click", "#btn-add-to-cart", function (e) {
    var productname = $(".displayproductdetails").data('name');
    var productimg = $(".displayproductdetails").data('img');
    var productprice = $(".displayproductdetails").data('price');

    $.ajaxSetup({ cache: false });
    $.ajax({
        url: "/Product/Cart",
        data: { name: productname, imgurl: productimg, price: productprice },
        cache: false,
        type: 'Post',
        success: function (data) {
            $('body').append(data);
        }
    });
})

}

My Controller Action:

[HttpPost]
    public JsonResult Cart(string name, string imgurl, string price)
    { 
        CartClass newcart = new CartClass();
        newcart.PictureImgURL = imgurl;
        newcart.ProductName = name;
        newcart.Price = float.Parse(price);
        newcart.Quantity = 1;
        return Json(newcart, JsonRequestBehavior.AllowGet);
     }

AngularJS Controller:

    var app = angular.module('Cart', []);
app.controller('CartController', function ($scope, $http) {
    GetCartData()

    function GetCartData() {
        $http({
            method: 'Get',
            url: '/Product/Cart'
        }).success(function (data, status, headers, config) {
            $scope.DisplayCart = data;
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
        });
    }
});

Lastly, my partial view:

@model IEnumerable<User_Public.Models.CartClass>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/AngularCart.js"></script>

<div ng-app="Cart">
    <div >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body" ng-controller="CartController">
                <div ng-model="DisplayCart">

                </div>
            </div>
            <div class="modal-footer">

                <button type="button" class="btn btn-success"> CheckOut</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </div>
        </div>
    </div>
</div>

My concerns:
1. Passing the model object from ASP Controller to AngularJS Controller
2. Storing it in local storage and displaying the data in the partial view.

I am open to alternative methods and technologies to achieve this. Since I am new to ASP MVC 4 and Angular JS, any additional code examples would be greatly appreciated.
Thank you.

Answer №1

Based on the MVC approach, your ASP.Net controller is set up for a HTTP POST request, while the AngularJS service is currently configured for a GET request. To resolve this discrepancy, you can either switch the ASP.Net controller action method to GET or adjust the AngularJS code to utilize the $http.post function instead.

If you're looking to incorporate local storage functionality, consider using libraries that provide wrappers for managing local storage within web browsers, such as the one available at https://github.com/grevory/angular-local-storage

Answer №2

Make sure that the cart object sent from the server is directed to the Angular Cart Controller instead of being directly placed in the body.

In your cart controller, initialize an empty array for cart items like this: $scope.cartItems = [];

Then, populate the cart items array with data obtained from $http.post either through a service or directly within the CartController.

By doing this, your ng-controller view will have access to the cart items in the Angular CartController, allowing you to use ng-repeat to display each item in a partial view. If you only intend to have one item in the cart, you can modify the approach accordingly and eliminate the need for an array.

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

Troubleshooting: Difficulty with jQuery script to change images

I am trying to modify the src attribute of an img tag using the code below, but it doesn't seem to be working. Can anyone help me figure out what's wrong? <img id='logo_image'/> <span onclick='$(logo_image).attr("src", "i ...

Guide to playing facebook in an iframe with javascript

I'm having trouble playing a Facebook video from an iframe using JavaScript. Can anyone help me figure it out? Here's what I've tried: <div onclick="play_fn()"> click here to play </div> <br> <script> function pla ...

Electron employee: Concealed BrowserWindow leads to delay in the interface

My worker runs in a hidden browser window and sends multiple requests simultaneously. However, these requests from the worker end up causing lag and freezes in the main browser window. Any suggestions for resolving this issue? ...

Accessing Google authentication: A guide to programmatically prompting user consent and retrieving the CredentialResponse after successful login

Is there a way to trigger the Prompt for User Consent to open when clicking a custom HTML button instead of the Login iframe button rendered by Google? I am utilizing the Sign In With Google JavaScript API, and while I couldn't find a function to achi ...

Enhancing Highcharts with realtime data streams using Socket.io

I'm currently working on a dashboard project utilizing node.js, socket.io, and highcharts. My main objective is to have the chart update in real-time upon receiving a request from socket.io. Does anyone have any suggestions on how to achieve this? ...

Is there a way to create an input mask that looks similar to this format --:--:--?

Is there a way to format an input in React to accept numbers in the format --:--:-- as 99:99:99 without using any plugins? Unfortunately, I am not sure how to achieve this with a simple input field. However, here is a snippet of code that I tried: <Tex ...

What is the best way to organize a list based on its textual content, which may consist of numbers

I am attempting to organize this list based on the distance (56km, 96km, 6km) from lowest to highest. I realize there are simpler ways to handle and add the li's to the ul, but I specifically require it in this format. The issue is that I am completel ...

Leverage Webpack's File-Loader to Import Images

I have implemented Webpack in my React application. I have added 'File-loader' & 'Url-loader' to my webpack configuration. But I am uncertain about how to connect images to my components. I'm storing the image source ('s ...

Creating a Vue 3 component and embedding it as an HTML string

Currently, I am tackling a project in vue.js (version 3) and find myself in a situation where I need to incorporate the HTML output of one component into another component's method. In my Vue project, I have developed an SVG component as shown below: ...

Enhance User Experience with React JS Multi-Select Dropdown Feature

I am dealing with 4 select dropdowns. The values selected should not be available in the remaining dropdown lists. Here is an overview of my state: this.state = { selectedDropdownArray: {}, dropdownArray: ['select', '1', &apos ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Null values are not allowed. Entity

I am currently working with a web API Attempting to send a request using Postman Below is the Model I am using using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace trackingappbackend.Models { us ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

What is the best way to incorporate this custom file upload button, created with vanilla JavaScript, into a React application?

Hey there! I have successfully implemented a custom file upload button using HTML, CSS, and JS. Now, I want to recreate the same design in React. Can someone guide me on how to achieve this in React? HTML Code: <br> <!-- actual upload which is h ...

Invoke a method on a ReactJS component class instance

Currently, I am working with a ReactJs class called Linker: var Linker = React.createClass({ foo: function(){ console.log('foo') }, render: function(){ return ( <div></div> ); } }); I am facing an issue wh ...

Original: Custom/Modified 'Fibonacci' Number sequenceRevised: Personalized/Altered

I am looking to create a unique variation of the Fibonacci sequence. The implementation I have in mind is as follows: (FSM) - FSM(0) = 0, FSM(1) = 1, FSM(n) = FSM(n - 2) + FSM(n - 1) / n How can this be achieved using JavaScript? Specifically, I need to ...

Java script request via Ajax is failing to execute

Within my HTML code, I have included a button like so: <button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button> Accompanying this is the JavaScript function send() : fu ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

Is there a way to verify past data in a Vue component post-rendering?

Currently, I am in the process of developing a straightforward market cap checker for cryptocurrencies similar to coinmarketcap by utilizing the Coingecko API. I have successfully managed to retrieve and display the data without any issues. Additionally, ...