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

Trouble with CSS transitions not functioning while altering React state

Each time a user clicks on an accordion, the content should smoothly show or hide with a transition effect. However, the transition only seems to work when opening a closed accordion, not when closing an already open one! To get a clearer idea of this iss ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

Protractor experiencing difficulty in adjusting price slider

As a newcomer to protractor, I am attempting to test a price slider that sorts products based on the provided price range. Unfortunately, I am facing difficulty in dragging the slider (min point) using protractor. Can anyone provide guidance on how to move ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

The current issue with Ajax and setInterval() is that the automatic updating of the text file is not

I am encountering an issue with updating two text files displayed on a web page through ajax. The script works perfectly on my localhost, but fails to update the files when hosted online. I have disabled caching of the ajax response, but still facing the s ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...

Develop a nested json object within another json object and send it back to Ajax

In my c# code, I am currently working with a List of Translations structured like this: public class Translations { public string en { get; set; } public string de { get; set; } } Now, I need to convert it into a Json Object because the function ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

Issue with jQuery Cycle causing images not to load in IE all at once, leading to blinking

When using the jQuery Cycle plugin in IE8 (as well as other versions of Internet Explorer), I am encountering an issue. My slideshow consists of 3 slides, each containing a Title, Description, and Image. The problem arises when viewing the slideshow in I ...

Adding click functionality to dynamically generated list items in jQuery and HTML

I'm encountering an issue while trying to assign click events to dynamically added HTML elements in jQuery. Despite extensive research within this community, I find myself more confused than before. Below is the snippet of code causing me trouble: v ...

Even after configuring a proxy, the API calls are still not being redirected to the correct destination

Even after setting up a proxy, the API requests are not being directed to the correct target URL. I've built a chatbot application with create-react-app. My goal is to reroute all API calls originating from http://localhost:3000/ to http://localhost: ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...

Reset jQuery validation when a button is clicked

I need assistance with a form validation issue. I am using jQuery validation methods to validate the controls on my form. However, I am facing difficulties in clearing the validation when clicking on 'cancel'. Below is the code snippet: <scr ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

Using Selenium to ensure the webpage waits for the external URL request

My objective is to obtain a link to a m3u8 file that requires a secret token which changes daily. The file is requested when the page first loads and is only available once the page is fully loaded. Using Chrome developer tools, I can see this file being d ...