Transform the post data into a JSON string within the controller

Hello everyone, I have a sample table that I want to share:

<table class="table table-bordered" width="100%" cellspacing="0" id="tableID">
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td align="center">val1</td>
      <td align="center">val2</td>
      <td align="center">val3</td>
      <td align="center">1500</td>
      <td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
    </tr>
    <tr>
      <td align="center">val1</td>
      <td align="center">val2</td>
      <td align="center">val3</td>
      <td align="center">1500</td>
      <td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)"  value="" min="0" max="1000"></td>
    </tr>
    <tr>
      <td align="center">val1</td>
      <td align="center">val2</td>
      <td align="center">val3</td>
      <td align="center">1500</td>
      <td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)"  value="" min="0" max="1000" ></td>
    </tr>
  </tbody>
</table>
<form>
<button type="button" onclick="aplicar()">Apply</button>
</form>
<script>
function setValueAttr(el){
  el.setAttribute('value', el.value)
}

function aplicar(){
    var myTab = document.querySelectorAll('#tableID tbody tr .txtID:not([value=""])');
    var tableData = [];
    Array.from(myTab).forEach(input => {
      var tds = input.closest('tr').children;
      var obj = {};
      obj.A = tds[0].textContent;
      obj.B = tds[1].textContent;
      obj.C = tds[2].textContent;
      obj.D = tds[3].textContent;
      obj.E = input.value;
      tableData.push(obj);    
    });
        tableData = JSON.stringify({ 'tableData': tableData });
            $.ajax({
            url: '@comercial.Models.Base.DirectorioRaiz()Controller/View',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: tableData,
            success: function (response) {
                $('#divPagosAplicados').html(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
}
</script>

I found a way to receive this JSON in my controller:

public class tableData
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
}


public void View(List<tableData> tableDatas)
{
    var t = tableDatas;

}

However, I need to perform an operation similar to the JavaScript function in my controller:

var total = [];
for (i = 0; i < tableData.length; i++) {
    total[i] = "&num_operacion" + (i + 1) + "=" + tableData[i].A +
        "&monto" + (i + 1) + "=" + tableData[i].E +
        "&num_documento" + (i + 1) + "=" + tableData[i].B +
        "&tipo_documento" + (i + 1) + "=" + tableData[i].C
}

I achieved this using JavaScript and sending the string with POST, but if the string is large, AJAX will crash.

Answer №1

To bind your expected model in the action method, make use of the [FromBody]ModelName helper.

public IActionResult([FromBody]List<MyModel> model)
{
............
}

Answer №2

Decided to create a separate Model instead of embedding the class within the Controller...

NewModel.cs

    public class tableData
    {
        public string A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
        public string D { get; set; }
        public string E { get; set; }
    }

Updated the controller as follows

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(List<tableData> tableDatas)
        {
            List<string> result = new List<string>();

            for(int i = 0; i < tableDatas.Count(); i++)
            {
                result.Add($"&num_operacion{i+1}={tableDatas[i].A}&monto{i+1}={tableDatas[i].E}&num_documento{i + 1}={tableDatas[i].B}&tipo_documento{i + 1}={tableDatas[i] .C}");
            }

            return Json(result);
        }

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

Searching Text Files Using PHP Based on User Input

I am in search of a way to check through a list of Zip Codes that we serve. We possess a text file filled with zip codes for the areas we cover. I would like to include a form on our website where users can input their zip code to determine if we provide s ...

Exploring the world of AJAX form with WordPress and making the most out of session variables

At my website, users have the ability to store session variables in two different locations. The first is through a PHP form on the single applicant page, and the second is through an AJAX form on the all applicants page. I utilize WP Session manager to ma ...

Guide to sending a post request in Node.js using Mongoose

I recently tried to follow a tutorial (https://medium.com/weekly-webtips/building-restful-apis-with-node-js-and-express-a9f648219f5b) from 2 years ago to build an API. However, I'm struggling to update the code to work with more recent changes in the ...

Is there a way to leverage JavaScript to click on one div and modify the settings of another div simultaneously?

I am struggling with my code which has unnecessary information. <div> <div id="one" class="button"></div> <div id="two" class="button"></div> </div> <div> <div class="Home tab"> < ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even t ...

The request.body in Express.js is currently undefined

const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()) app.use(cors()); app.post('/', (req,res) => { console.log(req.body); res.send('received') ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Display method JSONized

Looking for guidance on improving code efficiency and best practices. In my current project, I am working with a JSON Array structured like this: [ { "Date": "2014-07-16", "DiscPoint": "Description 1", "DisBy": "Person 1" ...

There are multiple ways to extract a value from Python code and assign it to a JavaScript variable in a JS file

I am currently working on developing the frontend for a voice bot using JavaScript, while the backend is written in Python. if hi == 0: talk('hello iam kavi') print('hello iam kavi Voice assistant') talk('How are you bu ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

Enhance the color scheme of your collapsed or expanded Bootstrap NAV for mobile devices

Currently working on customizing the navbar using Bootstrap. I've been able to style it perfectly for both desktop and mobile devices in its initial state. The issue arises when attempting to style the navbar in its expanded and collapsed states on m ...

An unhandled C# TypeInitializationException error surfaced in automatically generated code

When attempting to save an object (entity) in my database using the code snippet below, I encountered an unexpected TypeInitializationException: ctx = new UserEntities(); Users userDB = new Users(); userDB.name = user.firstName; userDB.surname = user.sur ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Tips on obtaining the data count from using the $.get method

Here is the code I'm currently working with: $.get('getstatsAccepted' + tickerid, {tickerid: tickerid}, function(data) { alert(data.length); }, 'json'); I am interested in obtaining the numbe ...

Using TypeScript gives you the ability to specify the type of an object while destructuring it,

Currently in the process of refactoring a NodeJS application to TypeScript. I have been consistently using object destructuring and have also been creating aliases while object destructuring, as shown in the code block below. My question is, how can I sp ...

What are the reasons for transitioning from using <script> includes to npm installs?

I am currently working on a VueJS project where I utilize npm to handle all Vue-related components such as vue-resource, router, and Vuex. However, in my index.html file, I have also included additional scripts like Bootstrap, jQuery, and Tween using scrip ...

The integration of Angular CLI with SCSS is no longer a separate process -

It seems like I might be overlooking something very straightforward here. After a fresh installation of angular-cli, I created a new website with SCSS. I input the SCSS in the global style.scss as well as some in a component SCSS file. However, when I se ...

The React Component is limited to updating once

Exploring the React Native code below: import React from 'react'; import {Text, View, StyleSheet, Button} from 'react-native'; export default class Target extends React.Component { constructor(props){ super(props); ...