Issue with Passing Complex Objects to Controller in .NET Core

I am attempting to encapsulate data forms into an object as shown in the image below...

https://i.sstatic.net/PK60S.png

Here is how I have structured my object in MVC:

Employee

public class Employee
{
    public int Position { get; set; }
    public int Salary { get; set; }
    public Biodata? Biodata { get; set; }
    public EmergencyContactPerson? EmergencyContactPerson { get; set; }
}

Biodata

public class Biodata
{
    public string Fullname { get; set; }
    public int Gender { get; set; }
    public string Email { get; set; }
}

EmergecnyContactPerson

public class EmergencyContactPerson
{
    public string Fullname { get; set; }
    public int Connection { get; set; }
    public string NumberPhone { get; set; }
}

After successfully wrapping the data, encountering issues when trying to send it to the controller. Below is my Ajax syntax:

$("#pageEmployee-input").ready(function () {
        $("#btnSave").click(function () {
            var biodata = {}, employee = {}, emergencyContactPerson = {};
            var test = $("#formBiodata").serialize()

            $("#formBiodata").serializeArray().map(function (x) { biodata[x.name] = x.value; });
            $("#formEmployee").serializeArray().map(function (x) { employee[x.name] = x.value; });
            $("#formEmergencyContactPerson").serializeArray().map(function (x) { emergencyContactPerson[x.name] = x.value; });

            var dataFormObject = {};
            dataFormObject.Position = employee.Position
            dataFormObject.Salary = employee.Salary
            dataFormObject.Biodata = biodata
            dataFormObject.EmergencyContactPerson = emergencyContactPerson

            var dataForm = JSON.stringify(dataFormObject)
            debugger
            $.ajax({
                url: "Home/Create",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: dataForm,
                success: function (data) {
                    console.log(data);
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

        })
    })

When debugging in the controller, the following issue arises... https://i.sstatic.net/1rj66.png

Help needed with fixing syntax or procedure.

Answer №1

Ensure that the data object type in JavaScript matches the object type in the .NET controller.

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

Create an angle-div element that can be expanded or collapsed without relying on

I'm currently experimenting with creating a diagonal div that adjusts its height based on the content within it. While I can extract height values using JavaScript, I am curious if achieving this effect is possible exclusively through CSS. Thus far, ...

Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) g ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...

Leveraging async/await in tandem with a for loop and mongodb

My goal is to send an order confirmation email using nodemailer to customers once they have completed their purchase. I also want to include some data from the purchased products in this email. I have tried various combinations of async/await but have not ...

How can I hide the title bar on screens in expo?

As a newcomer to the world of react-native, I rely on YouTube tutorials to assist me in creating projects. Currently, I am working on developing an expo ui-app, however, each screen I create displays a title at the top, such as this example: https://i.ssta ...

What is the optimal method to distinguish between routes within react-router-dom?

Recently, I worked on implementing routes for a small task. When I enter / in the URL, it redirects me to the login page. On the other hand, if I input /dashboard, it takes me to the dashboard with a persistent drawer using Material UI components. However, ...

Using CoffeeScript with Visual Studio 2012

After following the installation steps at , I successfully installed CoffeeScript on my system. Everything was running smoothly as the coffee code was compiled to JavaScript whenever I pressed ctrl + s. Recently, a colleague retrieved my code from the so ...

Tips for showcasing model data dynamically on a webpage using HTML

My model is constantly updating within a function, and I need a way to dynamically display this updated data without the need to refresh the page. How can I achieve this? models.py class MyLongProcess(models.Model): active_uuid = models.UUIDField(&apo ...

Uncovering the websocket URL with NestJS and conducting postman tests: A step-by-step guide

Creating a mean stack application using NestJS involves utilizing websockets. However, testing websockets in Postman can be confusing. Typically, I test route URLs in Postman and get output like: "http://localhost:3000/{routeUrl}". But when it comes to tes ...

Prompt user to save changes or cancel before closing modal (if closed by pressing ESC or clicking the backdrop)

When I manually close the modal, everything works fine. I just create a prompt and only call the BsModalRef.hide() method when the prompt (sweetalert) is closed. However, when the modal is closed using the ESC key or click-outside events provided by Boots ...

Is there a way to select an element within a nested list item only when the preceding list item is clicked using Jquery/JavaScript?

I am working with an unordered list that looks like this: <ul> <li><a class="foo" id="one">some text</a></li> <li><a class="foo" id="two">some text</a></li> <li><a class="foo" id="thr ...

Explore linked MongoDB collections using Node.js and Handlebars to access relevant documents

As a novice web developer, I've taken on the challenge of creating a bug-tracking platform for my project. The main issue I'm facing is displaying the user's name instead of their user ID in the "Reported by" column on the dashboard screensh ...

Saving data to a variable with AJAX/JSON when the column name is numerical: Best practices

When attempting to save a JSON value as a variable from an AJAX response ... $.ajax({ url:'example.php', type:'POST', dataType: 'json', success:function(data){ var checkname = data.name; // works fine var check1m = ...

What could be causing the chart to fail to load after I switch the JSON file

Today was my first day using highcharts and I ran into an issue when trying to use their provided code. When I changed the url of the json file, the graphic stopped loading. Original code: $.getJSON('https://www.highcharts.com/samples/data/jsonp.ph ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

Is there a problem with the refresh method in Javascript not functioning properly in Edge browser?

As I embark on my current project, a challenge presents itself: I require the page to automatically refresh once the music has concluded. Surprisingly, this code performed flawlessly on Chrome and Firefox. setTimeout(location.reload.bind(location), 206000 ...

Error: The function subscribe in _store_js__WEBPACK_IMPORTED_MODULE_12__.default is not supported

In my main App component, I am subscribing to the store in a normal manner: class App extends Component { constructor(props) { super(props) this.state = {} this.unsubscribe = store.subscribe(() => { console.log(store.getState()); ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

Java has its own robust framework, just like C# benefits from the presence of .NET

Is there a framework equivalent to .NET for Java? Whenever the topic of C# is discussed, .NET will undoubtedly come up, but I have not come across a similar defined framework for Java. ...