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

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

When using the Google Maps API fetch() method, the response is empty. However, when accessing the same

I am currently working on extracting the "photo_reference" from the JSON data provided below; { "html_attributions" : [], "results" : [ { "formatted_address" : "Bandar Seri Begawan, Brunei", "geometry" : { "locati ...

Is there a way for me to programmatically modify a .env file using an npm script?

Currently, I'm managing a project with a .env file that contains confidential information. One of the key elements in this file is 'STATUS'. Just to clarify, this pertains to a Discord bot, The value assigned to the 'STATUS' var ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

Looking to retrieve country, state, city, and area based on inputting a pincode value using Node.js?

I'm currently working on a web project with nodeJs and ejs. I am looking for a solution that can automatically update the country, state, city, and area fields based on the input of a pin-code (zip-code). Are there any recommended packages in node js ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

Passing "this" to the context provider value in React

While experimenting with the useContext in a class component, I decided to create a basic React (Next.js) application. The app consists of a single button that invokes a function in the context to update the state and trigger a re-render of the home compon ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

Verify all inputs are complete in the FullScreenForm

I have been working on implementing a form from this website: http://tympanus.net/Development/FullscreenForm/ My main objective is to validate each input when the form is submitted and display any errors that may arise. To achieve this, I have already se ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Discovering the Desired Key within a JSON Structure

For my c# project, I am utilizing the Json.net Library. Within this library, I have a lengthy JSON object with multiple subfields. Here is an example of the structure: { "count": 10, "Foo1": [ { "id": "1", "name": "Name1" }, { ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

Utilizing .NET MVC for incorporating HTML attributes with @HTMLTextAreaFor

I'm encountering an issue when trying to add HTML attributes to a text area using the @HTML command. Specifically, I am attempting to include a class name, but it doesn't seem to be working as expected. Below is the code snippet that I am workin ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Expanding Your jQuery Library from a Content Delivery Network

As of now, I have a jQuery hosted on my FTP along with other web files. YSlow recommends using a CDN for jQuery. However, I am wondering how I can extend that jQuery. Is it possible to add custom functions to it without being able to edit the original co ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

Preventing users from copying and pasting information from my form by implementing javascript restrictions

I'm looking for a solution to prevent users from copying and pasting in my form using JavaScript. I want to restrict the ability to paste or copy any content into the form. Any assistance would be greatly appreciated! ...