Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models:

public class CourseVm {
    public IList<CousreAttendance> CourseAttendances { get; set;}
}

public class CourseAttendance {
    public int StudentId { get; set; }
    public List<SessionAttendance> SessionAttendances { get; set; }
}

public class SessionAttendance {
    public int SessionId { get; set; }
    public bool IsPresent { get; set; }
} 

Sending a list of objects without inner-list properties works fine. However, sending the CourseVm object to the controller always results in failure. The desired format for input values is shown below:

// Before submitting the form to the controller
form.append('<input type="hidden" name="CourseAttendances.Index" value="0" />'+
            '<input type="hidden" name="CourseAttendances[0].StudentId" value="5" />'+

            '<input type="hidden" name="CourseAttendances[0].SessionAttendances.Index" value="0" />' +
            '<input type="hidden" name="CourseAttendances[0].SessionAttendances[0].IsPresent" value="true" />' +
            '<input type="hidden" name="CourseAttendances[0].SessionAttendances[0].SessionId" value="555" />' 

    // Replicate this logic for SessionAttendances[1..n]
  );

I prefer not to utilize @Html.HiddenFor() due to certain reasons, therefore, I need to generate hidden inputs using jQuery. Can someone guide me on how to create the correct input format? Thank you.

Answer №1

I have successfully resolved the issue at hand and am sharing my solution for the benefit of future readers. The solution involves two essential steps:

  1. Ensure all models have a parameter-less constructor. In my case, one of the models was lacking this.
  2. Create hidden inputs using the method outlined below.

I have created a method to generate an input for sending objects with multiple levels of lists. See the code snippet below:

function hiddenInputForComplexListItemWithListProperty(index, inputName, objectProperties) 
{
    // Function logic goes here
}
// Other supporting functions and methods included in the code

How to use: Suppose you need to submit a list of models like the example below to a controller:

{
    "Id" : 1,
    "CourseAttendances": [ 
                          {"StudentId" : 100, 
                           "SessionAttendances" : [{"SessionId":1, "IsPresent":true},
                                                   {"SessionId":2, "IsPresent":false}]
                          },
                          {"StudentId" : 101, 
                           "SessionAttendances" : [{"SessionId":1, "IsPresent":true},
                                                   {"SessionId":2, "IsPresent":true}]
                          }
                         ]
}

You would structure your object as follows:

// JavaScript code to append hidden inputs for each object in the list

To properly invoke the method for the sample JSON model mentioned above, the correct format is:

hiddenInputForComplexListItemWithListProperty(
    1,
    "CourseAttendances",
    [ 
     {"StudentId" : 100, 
      "SessionAttendances" : [{"SessionId":1, "IsPresent":true},
                              {"SessionId":2, "IsPresent":false}]
     },
     {"StudentId" : 101, 
      "SessionAttendances" : [{"SessionId":1, "IsPresent":true},
                              {"SessionId":2, "IsPresent":true}]
     }
    ]
);

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

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

jquery dialog content vanishing upon second opening

My jQuery code is set up to display a dialog when a button is clicked. The issue I'm experiencing is that after closing the dialog and reopening it, the text area within the dialog appears empty with only three buttons visible. However, upon subsequen ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

Exchange information among unrelated components

I'm working on implementing a vue event bus to facilitate event communication between my components. In my app.js file, I have included the line Vue.prototype.$eventBus = new Vue();. Within one component, I trigger an event using: this.$eventBus.$emit ...

The issue of the "port" attribute not working for remotePatterns in the Image component has been identified in Next.js 13's next.config.js

I've encountered an issue with the code snippet below. I'm attempting to utilize remotePatterns in my next.config.js file to enable external images. Strangely, when I set the port to an empty string "", it functions correctly. However, specifying ...

Include the distribution file from the npm package in the final build

Working on my react-based project, I've integrated the node-poweredup npm package to enhance functionality. This useful library comes in both a nodejs and browser version. To include the browser version in my app, I simply link the script located at j ...

Struggling to implement a sidebar in HTML using jQuery and running into issues?

I am struggling to create a template that includes a navbar, sidebar, and other elements that can be used across multiple HTML files. Despite trying different approaches, including changing the jQuery version and downloading jQuery, I am unable to make it ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

Encountering the issue of "Cannot read properties of undefined" while attempting to pass data to a prop

Currently, I am developing a Vue application that heavily relies on charts. The issue lies in the fact that I am fetching data from the database individually for each chart component, resulting in multiple calls and a slower page load time. I am looking to ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

When using a React Router path variable along with other paths, React may have difficulty distinguishing between them

Setting up react router in my project to differentiate between user username variables and other paths is proving challenging. For instance: baseUrl/admin baseUrl/daniel Currently, React is unable to distinguish between the two. My intention is to query ...

What is the correct way to incorporate Regular Expressions in Selenium IDE coding?

Using regular expressions to check for a correct answer from a prompt has been challenging. The current expression seems to be giving unexpected results, marking valid answers as false. For instance, when inputting the number 3, Selenium indicates that the ...

Can you explain the functions of this "malicious" JavaScript code?

I came across this piece of code on a website that labeled it as "malicious" javascript. Given my limited knowledge of javascript and the potential risks involved in trying out the code on my own site, I was hoping someone here might be able to shed some l ...

Observable in RxJS with a dynamic interval

Trying to figure out how to dynamically change the interval of an observable that is supposed to perform an action every X seconds has been quite challenging. It seems that Observables cannot be redefined once they are set, so simply trying to redefine the ...

Exploring the world of tweets using React

While trying to retrieve tweets using the Twit package, I keep encountering error 400. I received an error message stating: "Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: Response to prefligh ...

What could be causing the drop-down values to fail to be saved?

I'm dealing with an address object that has nested objects for both permanent and postal addresses. Despite successfully saving the values of input boxes in a large form, I'm facing an issue with not being able to save the dropdown (select) value ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...