Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that the calendar can interpret. In my current setup, I pass a ViewModel containing a list of a specific datamodel class as a property, and I need to figure out how to loop through this list in the view to make it compatible with the existing calendar structure.

//Existing Accepted Calendar Input

events: [
                {
                    title: "Birthday Party",
                    start: new Date(2020, 0, 1), 
                    end: new Date(2020, 0, 13),
                },
                {
                    title: 'Birthday Party 2',
                    start: new Date(2019, 11, 9),
                    end: new Date(2019, 11, 13),
                },
                {
                    title: 'Click for Google',
                    start: new Date(2019, m, 28),
                    end: new Date(2019, m, 29),
                }
            ],

//ViewModel for Calendar

 public class CalendarViewModel
    {
        public IEnumerable<CalendarDataModel> data { get; set; }
}

CalendarDataModel:

public class CalendarDataModel
{
    public string Description { set; get; }
    public int StartYear { set; get; }
    public int StartMonth { set; get; }
    public int StartDay { set; get; }

    public int EndYear { set; get; }
    public int EndMonth { set; get; }
    public int EndDay { set; get; }

}

My objective is to find a way to convert the data passed through the ViewModel into a json format that aligns with what the JavaScript-based calendar expects.

Answer №1

Transform the data into JSON format.

Within your perspective:

@using Newtonsoft.Json;

<script type="javascript">
    var events = @Html.Raw(JsonConvert.SerializeObject(Model.data))
</script>

You might have to adjust the property names using

[JsonProperty("add property name here")]
attributes in your model.

Answer №2

Maybe try implementing something along these lines?

let jsonData = @Html.Raw(System.Web.Helpers.Json.Encode(Model.data));
        let calendarEvents = [];
        jsonData.forEach(function (data) {
            let eventDetails = {
                title: data.Description,
                start: new Date(data.StartYear, data.StartMonth, data.StartDay),
                end: new Date(data.EndYear, data.EndMonth, data.EndDay)
            }

            alert(data.StartYear + "-" + data.StartMonth + "-" + data.StartDay)
            alert(data.EndYear + "-" + data.EndMonth + "-" + data.EndDay)
            calendarEvents.push(eventDetails);
        });

The "calendarEvents" array will store the information needed for your calendar.

Answer №3

To utilize the Json class from the System.Web.Helpers namespace, follow these steps:

Within your javascript code:

var data = @Html.Raw(Json.Encode(Model.info));

This will create an array structured as shown below:

[
    {
        'Name': ...,
        'Age': ...,
        'Gender': ...,
        'Location': ...
    },
    ... 
]

In my personal experience, it is recommended to always include Html.Raw when using Json.Encode to prevent incorrect encoding of characters.

You can then iterate through your model just like any regular array of Json objects:

for(var i = 0; i < data.length; i++) {
    // perform actions with data[i]
}

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

Difficulty encountered when utilizing json_extract function in Sqlite for a key containing a colon symbol

Below is a demonstration of an example data set: id|accountid|attributes|created|type 1|10|{'base:instances': '{}', 'cont:contact': 'CLOSED', 'cont:contactchanged': '1468516440931', 'devcon ...

Searching through a JSON object on a Laravel web page using JavaScript or AJAX for live filtering purposes

After diving into AJAX and JavaScript, I find myself needing to replace some outdated Angular functionality on our Laravel site. The specific task at hand is creating a live search filter for a page with a static header search bar. The main requirement is ...

Loop through a JSON object and save references in a Swift program

Upon receiving a JSON payload from a web request, the task at hand involves extracting the data and assigning it to variables within an NSObject subclass. The object contains the following variable declarations: var name:String? var email:String? var abo ...

Incorporate React Components into a traditional HTML, CSS, and JavaScript project

Can I incorporate a React Native Component (https://www.npmjs.com/package/react-native-gifted-chat) into my vanilla JavaScript project? Is it feasible to embed a React Native component within a vanilla JavaScript project? If yes, then what is the process ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

JavaScript: selecting multiple elements with identical attributes

I'm struggling to target all a tags with the 'data-caption' attribute. I attempted to do this by: first selecting all the a tags let links = document.querySelectorAll('a'); and then trying to access their attributes links.get ...

Sending JSON data through an AJAX post request will not work

After struggling for hours trying to debug this issue on my own, I've come to the point of seeking assistance. I need to send a substantial amount of data to an ashx handler and here's how it looks: var value = [{"start":["3,0"],"block":["0,0", ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Using React Hooks to render radio buttons within a map iteration

My code contains a nested map function where I try to retrieve values from radio buttons. However, the issue is that it selects all radio buttons in a row instead of just one. Below is the snippet of my code: <TableHead> <TableRow> ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Enhancing D3 visualization with centralized alignment and mobile-friendly responsiveness

I am still quite new to JavaScript and development in general, so I may be overlooking something obvious. Although I have successfully created a chart using d3, I am struggling with positioning. No matter how much I manipulate it with CSS, the chart just d ...

Check out the page design for section one!

I have been attempting to create a link to a specific section on a one-page website. Sometimes it works oddly, but most of the time it gets stuck at the section I clicked on and then manual scrolling does not function properly. From what I've researc ...

Using Vue JS to apply a filter to data fetched from an API

Within my code, I attempted to retrieve users with the role of Admin and only their usernames from the API JSON data. However, I encountered an issue where it did not work as expected. "response": [ { "profil ...

Transform the text column into JSON format

We currently have a resource bundle/properties formatted as follows: [tag1] server1 server2 [tag2] server3 server4 [tag3] server5 server6 [No Software Installed] server7 [tag2] server8 [tag5] server9 [tag1] server10 server11 [tag3] server12 server13 serve ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet: import React from &ap ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...