Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only a string value to the controller, my model ends up being null, and if I try to send the Javascript array, I receive a 400 (Bad Request) response.

The dynamic form I'm working on is for creating a Ticket, which consists of multiple Entries. Users can add as many rows as they need to fill out the required information such as: AccountNumber, AccountDescription, DebitAmount, CreditAmount, PostingDescription, PostDate.

Here's how the form table looks like:

@model Areas.TicketEntry.Models.FormTicketSubmissionModel
...
<div class="postDate">
    <label asp-for="PostDate" class="control-label"></label>
    <input id="PostDateInput" autocomplete="off" />
    <span asp-validation-for="PostDate" class="text-danger"></span>
</div>

<form action="Create" method="post" class="ticketForm">
    <div class="ticketTable">
        <table class="table" id="inputTable">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.AccountNumber)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.AccountDescription)
                    </th>
                    ...
                </tr>
            </thead>
            <tbody>
                ...

    <div class="formButtons">
        <button id="submitButton" type="button" class="btn btn-primary">Submit Ticket</button>
    </div>
</form>
...

How can I successfully submit an Array of Objects from Javascript to my Controller?

Any assistance would be greatly appreciated!

Answer №1

Upon reviewing @Llama's provided link, I decided to revamp my model(s) and form structure. Additionally, I discovered a mistake in my View's Form where I used

<form action="Create" .../>
instead of
<form asp-action="Create" .../>
, causing the form submission to trigger a 400 response error. The issue has been resolved without the need for JavaScript/Ajax.

New models:

public class FormTicketSubmissionModel
{
    [HiddenInput]
    public int Id { get; set; }

    // Stores the values of the entries 
    public FormTicketEntryModel[] TicketEntries { get; set; }

    [Display(Name = "Post Date")]
    [DataType(DataType.Date)]
    public DateTime PostDate { get; set; }

    [DataType(DataType.Text)]
    [RegularExpression(@"^[a-zA-Z0-9]*$")]
    public string UserName { get; set; }
}

public class FormTicketEntryModel
{
    [HiddenInput]
    public int Id { get; set; }

    [Display(Name = "Account Number")]
    public string AccountNumber { get; set; }

    [DataType(DataType.Text)]
    [StringLength(29, ErrorMessage = "Description is too long!")]
    [RegularExpression(@"^[a-zA-Z0-9+&.""/'\s-]*$")]
    [Display(Name = "Account Description")]
    public string AccountDescription { get; set; }

    [Display(Name = "Posting Description")]
    [StringLength(29, ErrorMessage = "Posting Description is too long!")]
    [RegularExpression(@"^[a-zA-Z0-9+&.""/'\s-]*$")]
    public string PostingDescription { get; set; }

    [Display(Name = "Debit Amount")]
    [DataType(DataType.Currency)]
    [Column(TypeName = "decimal(18,2)")]
    [Required]
    public decimal DebitAmount { get; set; } = 0.00m;

    [Display(Name = "Credit Amount")]
    [DataType(DataType.Currency)]
    [Column(TypeName = "decimal(18,2)")]
    [Required]
    public decimal CreditAmount { get; set; } = 0.00m;
}

Updated View:

<form asp-action="Create" method="post" class="ticketForm">
<input asp-for="Id" />
... (truncated for brevity)
        </table>
    </div>
    
    <div class="formButtons">
        <button id="submitButton" type="submit" class="btn btn-primary">Submit Ticket</button>
    </div>
</form>

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

I am having trouble getting my AngularJS client to properly consume the RESTful call

As I venture into the world of AngularJS and attempt to work with a RESTful service, I am encountering a challenge. Upon making a REST call to http://localhost:8080/application/webapi/myApp/, I receive the following JSON response: { "content": "Hel ...

Utilize Javascript to establish a fresh attribute by analyzing other attributes contained in an array within the object

Currently, I am working on a data structure that looks like this: masterObject: { Steps: [ { step: { required: false, }, step: { required: false, }, step: { required: false, }, }, ] } ...

What is the best method for converting a plist file into a json file?

Is there a way to convert an existing plist file into a JSON file using one of the following programming languages: JavaScript, Java, Objective-C, Python, or Ruby? Any suggestions on how to do this? ...

Utilize morris.js within an AngularJS directive to handle undefined data

Using the morris.js charts in my angular js app has been a great addition. I decided to convert it into a directive for better organization and functionality: barchart.js: angular.module('app_name').directive('barchart', function () ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

I often encounter network timeouts while attempting to send AJAX requests to my server

My current setup involves a React/Redux frontend deployed on AWS S3 and an Express/Mongo backend deployed on AWS EC2. While the application runs smoothly on most networks, I am encountering a timeout error when attempting to make AJAX calls from the fronte ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

Having trouble embedding Hangouts button in HTML template using script tags

When I include a Hangouts button on my index page, it is visible and functional as expected: <body ng-app="sampleApp" ng-controller="MainCtrl"> <div class="row"> <div class="col-md-12 m-body"> <div class="m ...

Some pages are compatible with JS while others are not... Although, the file can be found in the page source

I have limited knowledge in javascript, so I often find myself copy-pasting code. Currently, I am working on a website that includes a navigation sidebar. I have implemented a script to toggle a class that sets the display property to none. $(document).rea ...

The process of examining a function that includes the invocation of an additional API function in a NodeJS environment

I'm faced with a situation where I have a nested function inside another function. The second function is responsible for making an API call. However, in order to write a unit test for this scenario, I need to avoid actually making the real API call a ...

Passing information from Vue to a modal

I'm working with 3 components: TaskList, TaskItem, and TaskForm. Within the TaskList component, there is a loop that renders all the data in TaskItem. Each TaskItem has an edit button meant to open a TaskForm modal (using bootstrap) displaying the sp ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

What assistance is available for building a JavaScript package that integrates and utilizes all necessary dependencies?

I am looking for a solution to include a third-party library in a JavaScript file that will be downloaded to our project only when we visit a specific page. This library is installed with npm and I want it to be part of the js package without includi ...

What are some creative ways to represent data using different numerical intervals?

Looking to develop a visualization of a .CSV file containing 1.2 million lines, showcasing addresses in the format: source , destination 12.251.512 , 12.623.743 51.734.312 , 23.233.991 6334.6231.123 , 42.532.54453 (utiliz ...

Utilizing web components from NPM packages in conjunction with Svelte

My current project involves the development of a simple Single Page App (SPA) using Svelte. I have successfully implemented a basic layout and styling, as well as an asynchronous web request triggered by a button click. Now, my next objective is to utiliz ...

"Attempting to use a Chrome Extension to apply inline styles is not producing

Despite my attempts to search on Google, I have been unable to find a solution. I am currently working on developing a Chrome extension with the specific goal of changing/inserting the style.display property for one or more elements. This task would norma ...

What measures can be taken to ensure that the input checkbox is not toggled by accidentally pressing

There's a checkbox input in a dropdown menu at the top of the page that is giving me some trouble. When I select an option by clicking on it, for some reason pressing the spacebar toggles it off and on. Clicking outside once doesn't correct it, I ...