How can I properly bind a list of objects with nested lists when submitting forms?

Trying to bind a complex object that consists of nested lists of objects poses a challenge. While the data binds to the page successfully with pre-populated content, issues arise when posting the form to the handler method.

I can post and bind the parent object (ObjectA) along with its data-type properties and its list of complex objects (ObjectB). However, I struggle to bind the list of objects (ObjectC) within ObjectB.

To simplify, here's an example of what I'm trying to achieve:

Classes and handler method structure:

// Classes
public class ObjectA
{
    public int Id { get; set; }
    public IList<ObjectB> ObjectBList { get; set; }
}

public class ObjectB
{
    public int Id { get; set; }
    public IList<ObjectC> ObjectCList { get; set; }
}

public class ObjectC
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Handler method
public async Task<IActionResult> OnPostDoSomethingAsync(ObjectA objectA)
{
    // Do Something
}

Pseudo-code in .cshtml file using ClassA as the page model:

For simplicity, only hidden input fields are used in this example:

<form id="myFormId">
    <input type="hidden" asp-for="@Model.Id" />
    @for (var i; i < @Model.ObjectBList.Count(); i++)
    {
        var objectCList = @Model.ObjectBList[i].ObjectCList.Where(z => z.Id < 4);
        <input type="hidden" asp-for="@Model.ObjectBList[i].Id" name="ObjectBList[@i].Id" />
        @for (var z; z < objectCList.Count(); z++)
        {
            <input type="hidden" asp-for="objectCList[z].Id" name="ObjectBList[@i].ObjectCList[@z].Id" />
    }
</form>

The goal is to submit the form via both a submit button and Ajax. Testing has been done using an Ajax post like the one below:

$.post('/Page?handler=DoSomething', $(#myFormId).serialize(), function () { alert('success'); });

When the post action is executed with the code provided above, the payload displays content similar to this:

Id: 1
ObjectB[0].Id: 1
ObjectB[0].ObjectC[0].Id: 1
ObjectB[0].ObjectC[1].Id: 2
ObjectB[1].Id: 2
ObjectB[1].ObjectC[0].Id: 1
ObjectB[1].ObjectC[1].Id: 2

However, the issue arises when the handler receives null for the "objectA" parameter due to binding failure. It seems that the content received does not match the expected object model.

If I remove the CSHTML code related to binding ObjectC and only bind ObjectA and ObjectB, the payload changes to:

Id: 1
ObjectB[0].Id: 1
ObjectB[1].Id: 2

In this case, everything works correctly as ObjectA is populated as expected. It seems that introducing ObjectC breaks the binding process.

It is likely that there is an issue with how I am naming the input fields for ObjectC causing the incorrect payload. Any advice on the correct syntax for this scenario would be helpful. If my approach is sound, then there might be a typo or similar issue that needs to be addressed.

Answer №1

<input type="hidden" asp-for="objectCList[z].Id" name="ObjectBList[@i].ObjectCList[@z].Id" />

To test if the value is being set by asp-for="objectCList[z].Id", you can remove the type="hidden" and make a minor adjustment like this:

 @for (var i = 0; i < @Model.ObjectBList.Count(); i++)
 {
     var objectCList = Model.ObjectBList[@i].ObjectCList.Where(z => z.Id <4).Select(C => C.Id).ToList(); 
     <input type="hidden" asp-for="@Model.ObjectBList[i].Id" name="ObjectBList[@i].Id" />     
     @for (var z = 0; z <Model.ObjectCList.Count(); z++)
     {
         <input type="hidden" value="@objectCList[@z]" name="ObjectBList[@i].ObjectCList[@z].Id" />
     }
 }

Final outcome:

https://i.stack.imgur.com/po8TE.png

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 there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

Is there a way to transfer controller scope to a partial HTML file?

Welcome to my HTML setup <div ng-controller="filterController"> <div class="quick-view" id="quickview" data-toggle="modal" data-target="#modal-bar" ng-click="quickView(quickview)"><i class="fa fa-eye"& ...

Wordpress Ajax deeplinking leads to a 404 error page

Hey there, This is my first time posting here, and I want to say thank you for all the help I've already received by reading through previous posts. I'm currently working on a WordPress project, but I seem to be struggling to get a clear overvi ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...

Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encounte ...

Why does my ajax call return a file not found error after the session has expired?

My single page app has a login system that involves user authentication for session initiation. The server side sets a 30-minute session time, while the client side uses JavaScript to show a warning modal when nearing session expiration. However, this meth ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

The AJAX data submission did not go through as expected

I am facing an issue with two files on my site - home.php (view) and home.php (controller). In the home.php (view) file, I have a jQuery function that sends an AJAX request based on the W3 example. However, in the home.php (controller) file, the PHP variab ...

Secure your PHP file upload process by implementing restrictions to prevent users from uploading an unlimited number of files. Utilize

Question Update 2 : I have noticed that users can upload unlimited files and potentially take up all the disk space. How can I prevent this from happening? Update: Since no one has answered this question, is there a recommended source I could refer to f ...

Visualize data from ajax call in tabular format

I want to display the results of an SQL query in a table using AJAX. I have written code that executes the query during the AJAX call, but when I try to display these values in a table, it shows null values on the div tag. What could be the reason for this ...

"Utilizing AJAX to set an array as a global variable

Struggling with storing data values from an AJAX response XML into a global array, and then attempting to call a function that removes specific elements from it. The issue lies in the fact that the array is not declared as global. Here's the current c ...

Guide on dividing and presenting ajax information into two separate div containers

I am attempting to showcase two sets of data on separate divs using ajax. Below is the code I am utilizing for this task. Here is the ajax implementation $(function () { $(".myBtn").click(function () { var id = $(this).data("id"); ...

I incorporated an AJAX-based page into the PrimeFaces tab, but unfortunately, it is not functioning correctly

I've added different pages within prime faces tabs and used ID-based forms on each page. However, when I enable AJAX for each page it doesn't work properly within the tab. Here is a snippet of my primary index.xhtml page: index.xhtml <?xml ...

Several attributes in the JSON object being sent to the MVC controller are missing or have a null

I am facing an issue while passing a JSON object to my MVC controller action via POST. Although the controller action is being called, some elements of the object are showing up as NULL. Specifically, the 'ArticleKey' element is present but the & ...

How can I display a popup window when a validation event occurs?

Having trouble finding a suitable solution for my problem. Our MVC 3 application includes a form with Data Annotations for validation. The Email field has a RemoteAttribute to check for uniqueness. Here's what needs to be implemented: If the Email ...

Guidelines on managing two sets of JSON data sent via AJAX to a PHP script

Embarking on my journey into the realm of JSON/AJAX for the first time. Essentially, I am tasked with sending 2 sets of data to a PHP file. One set will be saved in a MySQL table, while the other is utilized by the PHP script. My Javascript generates 2 s ...

Jquery Ajax Request

My goal is to create an Ajax call with the following specifications: $.ajax({ type: "GET", dataType: "json", contentType: "application/json", username: "user123", password: "admin123", url: "http://localhos ...

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...

Having trouble with Yii login authentication, encountering this issue

In Yii, I have successfully implemented my project with working login authentication on one system. However, when I copied the same project to another system, I encountered the following error: session_regenerate_id(): Cannot regenerate session id - heade ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...