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

Is one round the limit for my JavaScript image slider?

After studying the JavaScript Chapter on W3Schools, I attempted to create an image slider. Initially, everything worked perfectly for the first cycle. For instance, when I clicked the next button, the slides continued to slide until the end of the slidesho ...

The form submission is being processed without any restrictions or limitations

<script type="text/javascript"> //$('#student').change(function() { $('#but').click(function() { var payid = $("#feType").val(); var course = $("#course").val(); var course_id = $("#course_id").val ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7. My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.b ...

The functionality of a website's design acts as a safeguard against unauthorized data transfers

I am encountering a major issue with my website. The layout I have created seems to be hindering me from making any modifications. My website consists of several containers, with three small containers stacked on top of each other as the main section of ...

Mastering the Art of Configuring Filters in Plupload

I am using plupload with a unique feature that allows me to select and upload files with extensions that are not defined in the settings. For instance, I can upload .rar or .txt files without explicitly defining them in the filters. $(".uploadDocs").cli ...

What is the method for retrieving a temporary collection in a callback function when using node-mongodb-native find()?

Is it possible to retrieve a temporary collection from a find() operation instead of just a cursor in node-mongodb-native? I need to perform a mapReduce function on the results of the find() query, like this: client.open(function(err) { client.collect ...

Antonio Mele's latest book on Django3 and Ajax Button Development

After clicking the like button, it shows a count of 2099 instead of 1. However, after refreshing the page, it displays the correct count of 1. The same issue occurs when unliking. The count is accurate only after a refresh, otherwise, it randomly shows eit ...

Enhance your interface with stunning JQuery code snippets

We are in the process of developing a web application that will be fully 2.0 compliant (utilizing AJAX and more). Although I am primarily a rich-client and server-side developer, my knowledge of Javascript is limited to a functional level. However, based ...

replace specific elements for cloze deletion evaluation

Consider this scenario: There are many reasons to succeed. (consisting of more than 5 words) phrases = ['There', 'are', 'many', 'reasons', 'to', 'succeed'] flashcards_count = ceil(len(phrase) / 3 ...

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...

The onclick attribute on a button in HTML is not functioning properly following the inclusion of an Ajax load

I am facing an issue with a button that is being dynamically loaded from PHP code using Ajax. The button has an onclick attribute that calls a function named viewImage. The Ajax request is triggered every 5 seconds inside the loadImages function. Snippet ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...

Detect Flash Player Event using Javascript

Is there a way to detect when a flash video ends without depending on user input like clicking the stop button? It's important to note: I HAVE NO CONTROL OVER THE PRESENTATIONS OR SWF FILES. My goal is to automate the client player object through s ...

Is the AJAX request from the same site as the reference file for JavaScript?

I've got a JavaScript file all set up on my website and it's running smoothly. Now I want to use the full URL of the script on another site by linking back to my own site. <script src="http://www-js.mydomains.com/some/path/file.js"></s ...

Tips for Sending Data in the Payload Instead of FormData

I am attempting to call an Alfresco service from a custom web-script, sending JSON data in the payload. Here is the Alfresco service: http://localhost:8080/share/proxy/alfresco/api/internal/downloads The JSON array I need to pass includes script nodes l ...

Exploring AJAX functionality in jsFiddle

Is there a way to work around the browser security restrictions and simulate jQuery's $.get() function to load data from a different domain in jsFiddle? /* It seems like this doesn't work in jsFiddle. */ $.get("http://www.google.com", functi ...

Transfer an array via Ajax to a Python server script

I need to send the names, values, and labels of my form elements when a button is clicked. Since the submit button messes up the order, I decided to handle it with JavaScript: $('#mybutton').click(function() { m.modal('show'); ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...