What is the method for converting JSON to a JavaScript object?

I am currently utilizing asp.net C#.

Here is the code snippet I have:

 CalendarInfo oInfo = new CalendarInfo { title = "Joe Bloggs", start = System.DateTime.Now.ToString("yyyy-MM-dd"), end = System.DateTime.Now.AddDays(3).ToString("yyyy-MM-dd") };
 var ser = new JavaScriptSerializer();
 JsonConvert.SerializeObject(oInfo);
 hdCalContent.Value = JsonConvert.SerializeObject(oInfo);
 ltCal.Text= JsonConvert.SerializeObject(oInfo); 

However, on the client side, I need the data to be in the following format:

[
    {
        title: 'All Day Event',
        start: '2016-06-01',
        end: '2016-06-10'
    },
    {
        title: 'Long Event',
        start: '2016-06-07',
        end: '2016-06-10'
    }
];

The issue with my C# code is that it generates something like "title:"Joe Blog", which is causing it not to work correctly. Can you help me generate the JSON in the exact format required for the client side? Below is my current client side code:

JSON.parse($("[id$='hdCalContent']").val())`

I'm eagerly awaiting a solution.

Below is a static version of the code that is valid and working with jQuery FullCalendar:

  $('#calendar').fullCalendar({
        theme: true,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2016-06-12',
        editable: true,
        eventLimit: true, // allow "more" link when too many events
        events: [
            {
                title: 'All Day Event',
                start: '2016-06-01'
            },
            {
                title: 'Long Event',
                start: '2016-06-07',
                end: '2016-06-10'
            },
            {
                title: 'Birthday Party',
                start: '2016-06-13T07:00:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2016-06-28'
            }
        ]
    });

In this case, the events will be fetched from the server side using C# code. I've implemented the code but it's not functioning as expected.

Answer №1

It is essential for your object to be placed in an array or another type that is enumerable.

CalendarInfo[] oInformation = new CalendarInfo[] { new CalendarInfo { title = "Joe Bloggs", start = System.DateTime.Now.ToString("yyyy-MM-dd"), end = System.DateTime.Now.AddDays(3).ToString("yyyy-MM-dd") }};


    hdCalContent.Value = JsonConvert.SerializeObject(oInformation);
    ltCal.Text= JsonConvert.SerializeObject(oInformation); 

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

Guide on how to have controller wait for promise to be resolved by an Angular service

Currently, I have a service that initiates an AJAX request to the backend. Service: function RetrieveCompanyDataService(options) { this.url = '/company'; this.Companies = undefined; this.CompaniesPromise = ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Exploring a designated pathway outside the confines of a Single Page Application using asp

I am currently developing a single-page application using asp.net core-3. My goal is to create two routes: /simulate -> This route takes you outside the SPA, to a basic controller that generates raw html /* -> any other routes will direct to t ...

Iterate through Javascript quotes and automatically navigate to the first quote once the loop is completed

I've encountered an issue with the script where I am unable to loop back to the first element once all child elements have been traversed. https://jsfiddle.net/pad5bp0o/2/ Here is the jQuery code snippet: $(document).ready(function() { var length ...

How can JavaScript be utilized to iterate through regex matches and divide a string into an array of segments separated by hyperlinks?

After receiving a string from an api, it appears like this: "If you <a href='https://example.com'>Click here</a> then <a href='https://example.net'>Click here</a>." I aim to construct an array that mir ...

Modifying Cell Appearance in a Word Document Generated Automatically

When generating invoices from my LightSwitch billing application, I am encountering an issue with the formatting of SubTotal, SalesTax, and Total Due cells in the Word document. The numbers appear as '4100.0000' instead of the desired format like ...

Challenges in Implementing Animated Counters on Mobile Platforms

My website is experiencing a strange issue with an animated counter. The counter works fine on desktop browsers, but when viewed on mobile devices in a live setting, it seems to have trouble parsing or converting numbers above 999. This results in the init ...

Include a text input field within the multipleTextBox component

How do I select a file and turn it into an option? For example, if there is a file on a server or my desktop, What is the best way to create a function that can handle this? Is AJAX the solution? <input type="text" name="name" value="text " ...

In the event that the user is authenticated within an iframe, proceed to redirect the parent window

Scenario - A situation has arisen where Site X needs to access Site Y through an iframe, both residing on separate servers. Current Progress - X has successfully accessed Y via iframe by adding the following code in the .htaccess file of Y: Header alway ...

Extract values from HTML IDs and store them in an array

Currently, I am working on a project where I need to capture a QR code and display it on the screen. After that, I want to iterate through the elements using a for loop and save the values in an array. Specifically, I am using the ID id="scanned-resul ...

What is the best way to showcase a single item from an array in Vue.JS?

Suppose I have a list of items in Vue.JS data () { return{ items: [ { itemID: 5, itemText: 'foo' }, { itemID: 3, itemText: 'bar' } ] } } Now, if I want to show the item with the itemID of 3 i ...

Develop a TypeScript class in a distinct file

I currently have ag-grid implemented in an Angular project with a CustomFilter. The problem is that the file containing the code for the CustomFilter function is becoming quite large and difficult to manage. I am now looking to move the CustomFilter to a s ...

AvaloniaUI and ReactiveUI causing UI to freeze during execution of async command

I am currently working on developing an MVVM Avalonia application using ReactiveUi. I am facing an issue where I want to run a command asynchronously to keep the user interface responsive. However, despite using async/await, the UI freezes when the command ...

Tips for accessing a PHP file across multiple domains

Currently, I am working with Core PHP and incorporating Javascript into my project. In this particular module, I am facing a challenge where I need to access data from one domain to another domain hosting the PHP file using Javascript for database storage. ...

Utilizing Hyperlinks in jQuery DataTables Cell with Data Pulled from Mysql Table

I have a question that builds upon the one before it: How to display a hyperlink in a cell with jQuery DataTables There is also a Fiddle link provided My current query revolves around implementing hyperlinks when fetching data from a MySQL database table ...

How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in ...

Experiencing issues with this.$refs returning undefined within a Nuxt project when attempting to retrieve the height of a div element

I am struggling with setting the same height for a div containing Component2 as another div (modelDiv) containing Component1. <template> <div> <div v-if="showMe"> <div ref="modelDiv"> <Comp ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

Regular Expressions in JavaScript can be used to search for patterns of text, such as finding a word containing

I need to validate user input. Users are allowed to use all characters, digits, "_" and "-". Currently, I am using the following code snippet to validate: myString.search(/\W/) != -1 It successfully validates everything I need except for the hyphen ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...