Serialization of objects is not possible in Angular JS post requests

At the moment, I am utilizing an AngularJS Post method to send data to my controller instead of a traditional form submission. The issue I am encountering is that after the post call, the object named sharingInfo in the controller always gets set to null. I suspect that this problem is related to the JSON serializer.

In Angular, the data is posted in the following manner:

$scope["TemplateForm"].$setPristine();
var model = getFormData($('#TemplateForm'));

model.Publish = publish;
model["Template.CommitteeWithAccessCanEditReusable"] = $scope.Model.Template.CommitteeWithAccessCanEditReusable;
model["Template.SharingInfo"]  = angular.toJson($scope.Model.Template.SharingInfo);
$http({
    method: "POST",
    url: "/Template/UpdateTemplateContent",
    data: model
}).then...morecode=>

While debugging, I noticed that the template.sharingInfo gets serialized as:

"{"CommitteesWithAccess":[{"TenantId":32727,"DisplayName":"20190304 Ted Test Committee","IsStatic":false,"RootCommitteeId":null}]""{"CommitteesWithAccess":[{"TenantId":32727,"DisplayName":"20190304 Ted Test Committee","IsStatic":false,"RootCommitteeId":null}]"

However, on reaching the controller, the debugger consistently shows the value as null. Although, for string or boolean types, I can successfully set the value. It seems like the object is not being properly serialized into the.NET object. To investigate further, I added a dummy sharingInfo variable of type string to check its expectations. This workaround is not ideal as it requires defining two variables with the same name but different types and prohibits any changes to the sharingInfo object.

Below is my controller method definition: where templatedto.sharingInfo is a string and templatedto.template.sharinginfo is the object

[AcceptVerbs(HttpVerbs.Post)]
        [RequireReusablesPermissions]
        public ActionResult UpdateTemplateContent(SaveTemplateDto templateDto)
        {

            if (templateDto.SharingInfo != null && templateDto.Template.SharingInfo != null)
            {
                templateDto.Template.SharingInfo = JsonConvert.DeserializeObject<ReusableDto.SharingState>(templateDto.SharingInfo) as ReusableDto.SharingState;
            }
            //just to see what this gives me tbd
            var serializedObject = JsonConvert.SerializeObject(templateDto.Template.SharingInfo);

            var validationResults = TemplateValidator.GetValidationErrors(templateDto);

            if (validationResults?.Any() == true)
            {
                return new AjaxResult<ReusableDto>
                {
                    ResponseResultCode = ResponseResultCode.Failure,
                    MessagesHeader = $"{Resources.UnableToSaveTemplate} {string.Join(",", validationResults)}"
                };
            }

The 'serializedObject' yields the following string:

"{\"CommitteesWithAccess\":[{\"TenantId\":32727,\"DisplayName\":\"20190304 Ted Test Committee\",\"IsStatic\":false,\"RootCommitteeId\":null}]}" 

It's evident that the Angular toJson and C# JSON serializer handle the serialization differently. How can I ensure that the expected serializing occurs in Angular?

Here is the object definition for reference. The reuasableDTO is template

     public class SaveTemplateDto
        {
            public ReusableDto Template { get; set; }
            public bool IsNewTemplate => Template?.Id == Guid.Empty;

            // Model binding properties 
            public bool Publish { get; set; }
            public string SharingInfo { get; set; }
        }

 public class ReusableDto
    {
        public SharingState SharingInfo { get; set; }

        public class TenantDto
        {
            public short TenantId { get; set; }
            public string DisplayName { get; set; }
            public bool IsStatic { get; set; }
            public string RootCommitteeId { get; set; }
        }

        public class SharingState 
        {
            public List<TenantDto> CommitteesWithAccess { get; set; }
            public List<TenantDto> CommitteesWithoutAccess { get; set; }            
        }

Answer №1

Consider creating a parent object

public class CommitteesWithAccessModel
{
    public SaveTemplateDto  SaveTemplateDto  {get; set;}
}

[AcceptVerbs(HttpVerbs.Post)]
[RequireReusablesPermissions]
public ActionResult UpdateTemplateContent(CommitteesWithAccessModel templateDto)
{
...
}

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

Display error messages in Vue.js

Within this component, I have a method that updates an employee. My goal is to display the error message in the view immediately after the "errorMessage" variable is assigned/changed within the "error" callback of the ajax call. var EmployeeEdit = Vue ...

When transitioning the Next application to Typescript, errors are displayed with JSX, but it functions correctly in the browser

After migrating my Next App from JS to TSX, I noticed that the JSX in my TSX file is showing errors and underlined, even though the app runs fine in the browser. I'm puzzled as to why this inconsistency exists. Can anyone provide assistance in resolvi ...

Maintain the structure of the slick slider during transitions

I am working with the slick slider and aiming to achieve a specific layout for the slider itself. What I require is a structure that looks like this: div div div div div I have managed to implement this design successfully, bu ...

Can a frontend framework be exclusively utilized on a single page within a completed project?

I have a project where I am looking to create a dashboard as the homepage, similar to this example: However, for this project, we are not using any frontend framework, only relying on JavaScript and jQuery. The backend for the project is implemented usi ...

"Implementing classes with AngularJS: A Step-by-Step Guide

Is there a way to dynamically add a class to the i tag after a button is clicked in AngularJS? <button type="button" title="Like" ng-click="countLikes(product.title)" class="btn btn-compare"> <i class="fa fa-thumbs-o-up"></i> </ ...

Encountered an error while handling a promise: Unable to access null properties (specifically, 'useState')

I'm having trouble understanding why I keep encountering this error with the line const [isLoading, setLoading] = useState(true);. It's initially set to true so it shouldn't be undefined. export default async function GetProducts() { c ...

Automatically closing jQuery UI Dialog with setTimeout Function

My goal is to automatically close a dialog three seconds after it opens. I have tried various methods but encountered some issues: setTimeout($("#mydialog").dialog('close'), 3000); Here is the code snippet in context: $("#acknowledged-dialog") ...

Ways to retrieve a specific value from a JSON string located deep within an array

The data in my array is as follows: $firstData=array ( '000' => array ( '000' => array ( 0 => '{"code":"11101000000","postal":"3310000","prefecture_kana& ...

Interactive Button Animation using Three.js

After importing a Mesh element into three.js from an fbx file, I am looking to enhance it with an effect similar to that of a clickable button. I am aiming to achieve the same pushable button effect as demonstrated in the first button style found on http ...

Having trouble initiating the webpack development server

As a newcomer to ES6, I decided to set up my development environment by following a guide for beginners. After completing all the steps as instructed, I reached the point of installing the webpack development server. Upon entering the command npm run bui ...

Retrieve data from JSON or JArray objects

In my JSON Array, I have data structured as follows: [ { "type": "type1", "id": "id1", "properties": { "sales": [ { "name": "name1", "req ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

Tab indicator modified to match the text's material design

I want the tab indicator to adjust its size based on the text. For example: https://i.sstatic.net/a8Y0I.png https://i.sstatic.net/xniMb.png Should I use JavaScript for this purpose? I am currently using Angular. Here is my HTML code: <div class="r ...

What purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

Server-side validation is the exclusive focus of the CustomValidator

I have an issue that needs addressing: On my Page, there are multiple validators, all of them except one perform both client side and server side validation. One validator only has server side validation. The dilemma: Currently, the Page is being submit ...

How can you display a div element when a checkbox is selected?

My goal is to dynamically display an input element if a checkbox is checked using ng-show. When a user does not have a telephone number, they can check the checkbox and then an input field should appear for them to enter their mailing address. Unfortunatel ...

Error: The method being called on this.props is not recognized as a valid function

I'm encountering an error in my code TypeError: this.props.* is not a function I've been trying to troubleshoot it but so far I haven't been able to identify what's causing the issue. I've attempted different methods, includin ...

Comparing a string array with dataset values in C# programming

I've written the following code: DataSet firstSet = new DataSet(); firstSet = cls.ReturnDataSet("RetriveData", new SqlParameter("@Field", "mark1"), new SqlParameter("@TblNm", "stud"), new SqlParameter("@WhereCla ...

Having trouble with Angular JS functionality

Today is my first day diving into AngularJS and I'm eager to learn more! Despite grasping the concept of how model-controller-views operate in AngularJS, I encountered an issue where the variables are not displaying as expected. Instead of the values, ...

<td> issue with IE not rendering overflow:hidden properly

In an effort to display text in a TD, I've implemented the overflow property set to hidden for the td element. Surprisingly, this code works flawlessly in Chrome, Safari, and Mozilla browsers, but unfortunately falls short in IE. Despite attempting to ...