Send the JSON output to the controller function

Hello there! I am new to asp.net mvc and I'm looking for a way to pass JSonResult data to a controller method. In my View, I have set up a table like this:

<table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-responsive nowrap" cellspacing="0">
            <thead>
                <tr>

                    <th>Item Code</th>
                    <th>Quantity</th>

                    <th>Unit</th>
                    <th>Item Description</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            @if (TempData["listOrder"] != null)
            {
                foreach (var items in TempData["listOrder"] as List<ebms.ViewModels.OrderItems>)
                {  @Html.HiddenFor(modelItem => items.Id, new { @id = "productId" })
                <tr>

                    <td id="productCode">@items.PRODUCT_CODE</td>
                    <td contenteditable="true" id="quantity">@items.QUANTITY_ORDERED
                        <input id="save" type="button" value="Save"  />
                    </td>
                    <td id="unit">@items.MEASUREMENT_NAME</td>
                    <td id="itemDesc">@items.ITEM_DESCRIPTION</td>
                    <td id="status">@items.tmpStatus</td>
                    <td>
                        @Html.ActionLink("Remove", "Remove", new { id = items.Id },
                                        new { onclick = "return confirm('Are sure want to remove?');" })
                    </td>
                </tr>

                }

            }

        </table>

The table values are populated from another source. However, the Quantity column has a default value of 0 as it needs to be inputted manually in the table.

Therefore, I have made the QUANTITY_ORDERED column editable so that users can enter the quantity directly in the table:

<script>

    $(document).ready(function () {
        $("#save").prop("disabled", true);

        $("div").on('input', function () {
            $("#save").prop("disabled", false);
        });

        $("#save").click(function () {
            var modifiedQuanity = {};

            modifiedQuanity.Id = $("#productId").text();
            modifiedQuanity.QUANTITY_ORDERED = $("#quantity").text();


            $.post("/Sales/Save", modifiedQuanity, function (msg) {
                $("#save").prop("disabled", true);
                $("#msg").html("<strong>" + msg + "</strong>");
            });

        });
    });

</script>

In my Controller, I have a JSonResult Method named Save which is intended to receive the QUANTITY_ORDERED value from the view.

        public JsonResult Save(ORDER_DETAILS obj)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                ORDER_DETAILS existing = db.ORDER_DETAILS.Find(obj.PRODUCT_ID);
                existing.QUANTITY_ORDERED = obj.QUANTITY_ORDERED;
                db.SaveChanges();
                return Json("Order saved successfully!");
            }
        }

I need to then pass the JsonResult data to a Controller Method for final saving.

However, I am facing an issue where the value doesn't seem to get passed to the Save Method. Can you help me figure out what I might be missing in order to successfully pass the JsonResult data to the Controller Method?

Answer №1

It is recommended to update

$.post("/Sales/Save" 

to

$.post('@Url.Action("Save", "Sales")'

By doing this, MVC can ensure that the link to the controller action is accurate.

Additionally, if you intend to send the data to a different method named "AddOrder" rather than directly saving it within the "Save" method.

If we assume that the method signature is for a static method within a class named "MyOtherClass" and it accepts an ORDER_DETAILS instance as a parameter, the code would look like this:

public static void AddOrder(ORDER_DETAILS details)
{
   //... add code here
}

In this scenario, the "Save" method would be simplified like so:

public JsonResult Save(ORDER_DETAILS obj)
{
   MyOtherClass.AddOrder(obj);
   return Json("Order saved successfully!");
}

If the specific method details differ in your case, adjustments will need to be made according to your exact requirements.

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

What is the process for accessing extra scope information with next-auth?

I have integrated next-auth with Discord authentication and included guilds in my scope, but I am unable to retrieve the guild data. How can this issue be resolved? const options = { providers: [ Providers.Discord({ clientId: process.env.DISC ...

Automated submission feature for Angular scanning technology

As a newcomer to angular.js, I am dedicated to learning the ins and outs of the framework. Recently, I created a form that enables me to search using a barcode scanner, followed by pressing a submit button. However, I find this process redundant as I wou ...

The issue with Framer motion's whileInView is that it does not animate the element when it is within the viewport in Next.js

In my current Next.js 14 project with the App Router, I decided to play around with animations using Framer Motion. One specific feature I wanted to implement was animating text elements into view as they enter the viewport. The idea is for the text to gra ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

Encapsulating JSON responses using a structured approach in PHP with the Laravel framework

I am currently developing a REST API that will generate diverse JSON responses based on the type of User making the request. A unique endpoint: example.com/api/v1/collect is utilized, employing Laravel's API authentication to fetch the User model wit ...

Exploring the magic of Spring MVC with the power of Ajax

Is it possible to utilize Ajax in Spring MVC without using <mvc:annotation-driven/>? If yes, then how would I map my controller in app-servlet.xml? I've come across numerous examples with annotations but nothing without them :( Thank you. ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

An alternative solution for supporting Edge Chromium is utilizing synchronous AJAX requests within the beforeunload event

While attempting a synchronous ajax request during the beforeunload event, I encountered an error stating that synchronous ajax requests are not supported in chromium browsers during page unload events. I am seeking alternatives for making a synchronous a ...

Encountering a null pointer error when trying to map JSON fields to a POJO

I have a JSON string as shown below. I am trying to map only the TYPE and UN_NUM fields from the SEGMENT object to a POJO, but my code is returning null values. test.json { "TEST": { "NAME": "PART_TRAN", "VERSION": "9.0", "ID" ...

The render props on the child component are not appearing on the screen as expected

Recently diving into React Native, I created a stateless component designed to iterate through props that contain objects with arrays of tags. The goal was to extract and display a single tag from each array item. (Refer to the console log in the screensh ...

Understanding how to retrieve the FileType from a Document Object Model using JavaScript

Looking at this DOM structure, we have an image with the following details: <img id="this-is-the-image" src="http://192.168.1.100/Image_tmp/2016-06/d4eb8d"> The task at hand is to click a button, execute a JavaScript function, and download the ima ...

Can someone guide me on how to locate and access the port number?

In my Reactjs project root directory, I've created a .env file. This is what's inside my .env file: PORT = 30001 ... In my App.tsx file, I'm trying to access the port like this: const PORT_NUMBER = process.env.PORT; When I run yarn start ...

How to extract a specific part of a string with regular expressions

I am currently working on a function to search for a specific substring within a given string. // the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value> var test = "1~abc1|2~def2|1~ghi3|4~jk-l4 ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

C# Rest Client Tool that Works with Various REST API's

I am looking to develop a REST client in C# that can dynamically read API call details from a configuration file, process the JSON responses received, and generate corresponding CSV files. Additionally, there will be another configuration file specifying a ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Service has not been properly declared

I encountered an issue with AngularJS where I am struggling to import a Service from one module to another. In the Data module, I have a Service named MenuDataService that I need to utilize in the MenuApp module. However, when attempting to do so, I receiv ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...