Refreshing data with AJAX in MVC 3 view

Below is the controller method:

    [HttpPost]
    public ActionResult CheckInventory(int itemID, short quantity)
    {

        Item model = db.Items.Single(x => x.Item_ID == itemID);
        model.Quantity_In_Stock = quantity;
        db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
        db.SaveChanges();
        db.Refresh(System.Data.Objects.RefreshMode.ClientWins, model);
        var newModel = db.Items.Single(x => x.Item_ID == itemID);

        return View("Details", newModel);
    }

Here is the AJAX code snippet:

    <script src="/Scripts/jquery-1.5.1.min.js" 
    type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(".UpdateItem").click(function () {
                var stockQuantity = 123;
                var iId = $(this).attr("data-id");
                if (iId != '' || iId != null) {
                    $.post("/Item/CheckInventory", { "itemID": iId, "quantityInStock": stockQuantity },
                              function (data) {
                                  $('#quantity-in-stock').text(stockQuantity);
                              });
                }
                else {
                    alert("Item ID is empty");
                }
            });
        }); 
    </script>

The link to trigger the action:

    <div>
        <a href="#" class="UpdateItem" data-id="@Model.Item_ID">Update</a> 
    </div>

Displayed table with updated information:

    <fieldset>
        <legend>Item Details</legend>
        <div class="display-label">
            <table>
                <tr><td>Quantity in Stock:</td><td><div id="quantity-in-stock">@Html.DisplayFor(model => model.Quantity_In_Stock)</div></td></tr>
            </table>
        </div>
    </fieldset>

Despite no error messages, clicking the link does not trigger any action and only adds a # to the URL. Both breakpoints in the controller's CheckInventory method and the AJAX function are not being reached. Any assistance would be greatly appreciated.

Answer №1

Ensure consistency in your key names and CheckStockmethod parameters - the ajax request mentions unitsInStock, while the CheckStock method uses units. Align them for seamless functionality.

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

Learn the process of merging an array element into another object and keeping track of the total count

Initially, my array contains object elements as shown below: $scope.selectedIngredient = [object1, object2, object3, object1, object2]; Next, I have a new object : $scope.selectedIngredientResults = {}; Now, I want to create a JavaScript function that ...

What specific characteristic of TypeScript's number data type or the Math.ceil() function is responsible for this calculation mistake?

Currently, I am working on a function in Typescript that is supposed to generate a unique number each time it runs. However, there seems to be a problem with the arithmetic as the results are not always correct. Upon further examination of the code below, ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Unsatisfied Dependencies in NPM

Despite searching extensively on SO and across the web, I have yet to find a solution to my issue. I am in the process of creating a package of React Native components for use in various other React Native projects. The goal is for other teams to simply ad ...

"Ensuring that every" within handlebars js

I have been exploring handlebars.js (hbs) and although I haven't mastered it yet, I am curious to know if there is an equivalent to the following code: {{#if all source}} If not, how can I create a similar functionality using handlebars.js? ...

If a div is hidden, disregard this particular CSS rule

In my current scenario, I am dealing with 3 distinct divs: - Menu - Header (#rt-top-surround) - Showcase (#rt-showcase) - Main Body content (#rt-mainbody-surround) The Menu is set as 'sticky' with position: fixed. As a result, I have to adjust ...

In ES6, the hoisting of block-scoped variables into the for loop header in

Do block scope variables in a for loop get hoisted above the loop header? var y = 4; for(let j = 3; j < y; j++) { let y = 2; ... } Will this trigger a dead-zone error on y each time j is compared to y in the loop header? I ...

What is the recommended approach for running a Node.js application in a production environment on a Windows operating system?

I am currently working on a Node.js application that needs to run on a Windows Server. During development, we usually start the app by running a command in either the command-line or PowerShell: node index.js What is the most efficient and recommended way ...

How can I send a JSON object or array as an argument to a directive in Angular?

My app is currently set up with a controller that retrieves data from a JSON file and uses "ng-repeat" to iterate through it. Everything works as expected, but I also have a directive that needs to do the same. The issue is that I cannot request the same J ...

In what way does Google Maps display map information at various zoom levels?

I am interested in developing an intricate electronic circuit using HTML. My goal is to display every aspect of the circuit in different levels of zoom, similar to how Google Maps functions. I am curious about the inner workings of Google Maps and how th ...

Avoid overwriting the success response parameter in jQuery Ajax

I've encountered a perplexing issue where the response parameter from the first ajax call is being overridden by the second call's parameter. Here is the code snippet: http://pastebin.com/degWRs3V Whenever both drawDonutForExternalLogin and dra ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Tips for implementing a countdown timer with JavaScript

I have created a program using HTML that functions like a website but works offline. I am looking to incorporate a 35-minute countdown timer that will automatically log out the user once the time is up. However, my current JavaScript code only counts down ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

Pass the values of both buttons to a different page using PHP

I am currently developing a system for a hospital. The data is sourced from an array and I need to pass the values from two buttons to another page. For example, on the initial page: 1 xyz First 2017-04-08 11:35:00 body checkup Generate Presc ...

Extracting targeted data from a JSON object

Obtaining a specific value from a JSON string can be more challenging than expected. For instance, how can I extract the 'name' of the first ModuleAction object from the JSON below (the first array is named 'data'): [ { "Modul ...

When using jQuery 1.7 or higher, the on(click..) function may not function correctly on dynamically added <li> elements

Currently, I am working on a dialogue that contains an unordered list with various suggestions. The HTML code for this section is as follows: <ul id="suggestions0"> <li id="suggestion0-0" class="suggestion">BLO</li> <li id="su ...

Can you show me how to access the elements of a JSON object named "foo.txt" and print them out?

Currently, I am working with JavaScript and JSON. My goal is to retrieve data from an API where objects contain specific details. Specifically, I need to display the details of an object named "foo.txt" which includes elements such as size, raw_url, conten ...

What is the best way to pass card data between Vue.js components?

My application consists of two components: DisplayNotes.vue, which displays data in card format retrieved from the backend, and UpdateNotes.vue, which allows users to update existing data by opening a popup. The issue I'm facing is that when a user cl ...

Passing an arrow function as props results in an error of undefined

When passing event handler functions as props to child components, regular functions are received but not fat arrow functions. import React, { Component } from "react"; export default class FruitClass extends Component { bananaEvents = { color: thi ...