Passing Table values from a View to a Controller in ASP.Net MVC

In my view, I have created a table that functions as a timesheet with an option to add more rows using a button.

<table class="table table-bordered table-responsive table-hover" id="mytab" cellspacing="0" cellpadding="0">  
        <thead>
            <tr>  
                <th>Project</th>   
                <th>Discipline</th>  
                <th>Mo</th>  
                <th>Tu</th>  
                <th>We</th>  
                <th>Thu</th>  
                <th>Fri</th>  
                <th>Sat</th>  
                <th>Sun</th>  
                <th></th>
            </tr>  
        </thead>
        <tr>
            <td><select name="selectedProjectId" asp-items="@ViewData["projectSubProject"] as SelectList" class="form-control-plaintext align-content-around">
            </select></td>  
            <td><select name="selectedPositionId" asp-items="@ViewData["Positions"] as SelectList" class="form-control-plaintext align-content-around"></select></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td>  
            <td><input class="form-control-plaintext align-content-around txtCal" type="number" min="1" max="24"/></td> 
        </tr>
    </table> 
    <br />
    <form action="">
        <input type="button" value="Add a Row" onclick="addRow()">
    </form>

Click here to see how it looks on the webpage

The script for adding rows and sending table data in JSON format to the controller on table data change is written like this:

$(document).ready(function(){
         // JavaScript code for calculating total sum goes here...
});

// JavaScript functions for adding rows, cloning elements, and cleaning up inputs

// JavaScript function for handling table data changes and sending to controller

Below are my controller methods:

public async Task<IActionResult> TableList()
    {
        // Controller logic for initializing view data
    }

    [HttpPost]
    public async Task<IActionResult> TableList([FromBody] List<object> data)
    {
        // Controller logic for processing table data
    }

I seem to be facing an issue where the JSON data doesn't reach the controller. Any insights on what might be going wrong?

UPDATE:

After resolving some issues, the data sent to the controller seems incorrect. https://i.stack.imgur.com/5aVnw.png

The selected options from select fields and numbers are not being captured correctly. I have updated all code to reflect the current state. Any suggestions or guidance on how to fix this would be greatly appreciated.

Answer №1

One approach could be creating a Model, like a Row class list, to handle that task.

Here is an example:

public class Row
{
    public string Project   {get;set;}
    public string Discipline {get;set;} 
    public string Mo  {get;set;}
    public string Tu  {get;set;}
    public string We  {get;set;}
    public string Thu  {get;set;}
    public string Fri  {get;set;}
    public string Sat  {get;set;}
    public string Sun  {get;set;}
}

public class TableModel
{
    public List<Row> Rows {get; set;}
}

Next, you can define all the functions to interact with this model.

This method can simplify your tasks and streamline your workflow.

I recommend checking out the Microsoft documentation for further insights on using models effectively.

Answer №2

When utilizing ajax to send a post request to your controller in asp.net core MVC, there are key considerations to keep in mind. Unlike the default form submission process, it is important to note that [ValidateAntiForgeryToken] and if (ModelState.IsValid) may not be appropriate for your specific scenario.

Additionally, when setting the request data using data: JSON.stringify(data), it will create a payload that cannot be received as a simple string. Instead, it is necessary to utilize List<object> data to properly handle the incoming data:

https://i.stack.imgur.com/oWAK6.png https://i.stack.imgur.com/vdM2G.png https://i.stack.imgur.com/nSWlo.png

To adjust your code accordingly, consider making modifications similar to the following example:

@section Scripts{
    <script>
        $("#btn1").click(function(){
            var data = [];
            var row1 = [1, 2, 3, 4, 5];
            var row2 = [6,7,8,9,10];
            data.push(row1);
            data.push(row2);
            $.ajax({
                url: "https://localhost:7175/Home/TableList",
                type: "post",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data);
                }
            });
        });
    </script>
}

[HttpPost]
//[ValidateAntiForgeryToken]
public string TableList([FromBody]List<object> data)
{
    //if (ModelState.IsValid) { 
    //    var list = JsonConvert.DeserializeObject(json);
    //}
    return "hello";
}

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

C# - Parsing JSON with JObject - Incorrect JSON Format

I am currently handling an API that returns JSON data. There is a method in place that calls the API and extracts the necessary nodes from the JSON response. Everything has been working smoothly so far, but the latest JSON response seems to be malformed. ...

Perform a Node.js GET request following a previous AJAX POST request

Having a major issue with using AJAX... I am not receiving the expected 304 page after a successful AJAX request... here is my code snippet: $.ajax({ url: "/crawling/list", type: "POST", dataType: "json", ca ...

Refresh MySQL database using AJAX

In my form, there are both a submit button and a close button. When a user enters information and clicks the submit button, an answer is posted and saved in the database. If the user chooses to click the close button instead, the entry in the database will ...

Troubleshooting XhrIo issue with Google Closure on Internet Explorer

When I added the try block to the code below, it started alerting Error: Could not complete the operation due to error c00ce56e.. goog.require("goog.dom"); goog.require("goog.net.XhrIo"); goog.require("goog.structs.Map"); goog.require("goog.Uri.QueryDat ...

Download files using AJAX in Laravel 5.6

I am faced with a challenge in my Laravel 5.6 REST API. Users have the capability to upload their files to a non-public folder. Now, I need to ensure that users can only download files if their JWT token is valid and they have the necessary privilege. H ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

The WooCommerce mini cart fails to refresh after items are added using AJAX

I have successfully implemented adding multiple items with quantities to the cart using AJAX. However, after adding a product, the mini cart is not updating as expected. I am calling WC_AJAX::get_refreshed_fragments() in my function.php and have a hook set ...

What is the process for updating EJS template with AJAX integration?

Understanding the combination of EJS with AJAX has been a challenge for me. Most tutorials on AJAX involve using an API that responds with JSON objects. Below is an example of code: router.js router.get('/jobs', function(req, res) { Job.fi ...

Is there a way to make a checkbox uneditable without actually disabling it?

I am encountering difficulty in resolving an issue. Within my application, I create text-inputs, checkbox inputs, and a select element. There are instances where I need to pre-fill these values for the user and prevent them from being modified. These elem ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

How about incorporating AJAX into your HTML code?

I am currently in the process of developing an email system for a company that wishes to use it for sending emails. To achieve this, I have implemented a custom HTML editor for creating email content. My goal is to post the email contents to an external PH ...

Encountered a system error in C# Selenium with Firefox, as the expected browser binary location was missing and unable to be found in the default location

I am attempting to utilize Selenium with C# and encountering the following error message: System.InvalidOperationException: 'Expected browser binary location, however unable to locate binary in default location. No 'moz:firefoxOptions.binary&ap ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Refreshing an HTML snippet with Django Ajax response through Class-Based Views (ListView)

On my homepage, I have a base listview displaying all objects from my database using the cbv .all() query. To add a search filter feature, I decided to create a reusable "list.html" fragment. Currently, an ajax call sends information to the cbv and returns ...

Convert the PHP variable into a JSON object

i am currently working on a project with Codeigniter below is my PHP switch-case section case 'check': $balance = $this->Model_transactions->getUserBalance($this->input->post('userId')); $needToPay = floatval($this->inp ...

Execute custom time intervals for running jQuery ajax requests

I'm working on a jQuery ajax function that needs to be executed at specific intervals. It should not run on page load, but instead start after 5 minutes and then repeat every 5 minutes thereafter. Below is the code I am using: jQuery(document).ready ...

Encountered an unexpected "<" error while using Ajax with MySQL

I am trying to accomplish a simple task - retrieve a table from a MySQL database. Previously, I was using basic MySQL code and it was working fine. However, after switching to MySQLi, I encountered an error: Uncaught SyntaxError: Unexpected token < ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...