Utilize a WebAPI controller to serialize a complicated JSON object

Embarking on a new journey with AngularJS and ASP.NET WebAPI, I find myself faced with the challenge of working with base tables structured as follows:

CurriculumID    SubjectArea CourseNumber
------------    ----------- ------------
303     GHIJ        101
304     ABCD        102
305     MNPQ        103
306     WXYZ        104

lookupId    lookupValue
--------    -----------
1       Very Useful
2       Somewhat Useful
3       Not Useful
4       Not Applicable
5       Elsewhere

To tackle this requirement, I've created model classes (course and lookup) for these tables. Now, my quest is to generate JSON data in the backend using a web API controller method

public HttpResponseMessage getData(...)

The desired JSON output should be structured as follows:

    $scope.questions = [
    {
        "CurriculumID": "303", "SubjectArea": "GHIJ", "CourseNumber": "101", "answers": [
         { "lookupValue": "Very Useful","lookupId":"1" },
         { "lookupValue": "Somewhat Useful", "lookupId": "2" },
         { "lookupValue": "Not Useful", "lookupId": "3" },
         { "lookupValue": "Not Applicable", "lookupId": "4" },
         { "lookupValue": "Elsewhere", "lookupId": "5" }
        ]
    },
    {
        "CurriculumID": "304", "SubjectArea": "ABCD", "CourseNumber": "102", "answers": [
         { "lookupValue": "Very Useful","lookupId":"1" },
         { "lookupValue": "Somewhat Useful", "lookupId": "2" },
         { "lookupValue": "Not Useful", "lookupId": "3" },
         { "lookupValue": "Not Applicable", "lookupId": "4" },
         { "lookupValue": "Elsewhere", "lookupId": "5" }
        ]
    }
.
.
.
];

For further insights, refer to this link: https://plnkr.co/edit/73oA3rsrre8gqYX9V25W?p=preview

I'm seeking guidance on constructing the two methods getData to serialize this structure in ASP.NET. Any assistance towards achieving this serialization would be greatly appreciated.

https://plnkr.co/edit/73oA3rsrre8gqYX9V25W?p=preview

Answer №1

Assume you have structured your SQL tables with the given entities:

public class Question
{
    [Key]
    public int CurriculumID { get; set; }

    public string SubjectArea { get; set; }

    public int CourseNumber { get; set; }
}

public class Rating
{
    [Key]
    public int LookupId { get; set; }

    public string LookupValue { get; set; }
}

The next step involves creating a view model that mirrors the desired structure for serialization:

public class QuestionViewModel
{
    public int CurriculumID { get; set; }

    public string SubjectArea { get; set; }

    public int CourseNumber { get; set; }

    public IList<RatingViewModel> Answers { get; set; }
}

public class RatingViewModel
{
    public int LookupId { get; set; }

    public string LookupValue { get; set; }
}

Subsequently, within your controller, you can retrieve the entities from the database and populate the view model accordingly:

public class QuestionsController: ApiController
{
    [HttpGet]
    [Route("api/questions")]
    public IHttpActionResult Get()
    {
        using (var db = new MyDbContext())
        {
            IList<Rating> ratings = db.Ratings.ToList();
            IList<Question> questions = db.Questions.ToList();
            IList<QuestionViewModel> result = questions.Select(q => new QuestionViewModel
            {
                CurriculumID = q.CurriculumID,
                SubjectArea = q.SubjectArea,
                CourseNumber = q.CourseNumber,
                Answers = ratings.Select(r => new RatingViewModel
                {
                    LookupId = r.LookupId,
                    LookupValue = r.LookupValue,
                }).ToList(),
            }).ToList();

            return this.Ok(result);
        }
    }
}

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

The Angular 2 Router's navigation functionality seems to be malfunctioning within a service

Currently, I am facing an issue with using Angular2 Router.navigate as it is not functioning as expected. import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router } from '@angular/ ...

What is the method for enlarging the width of the nvd3 chart timespan?

Click here In the Plnkr linked above, I have included the latest versions of d3 and nvd3 libraries. Upon initial viewing of the chart, you may notice that all the timespan ticks such as 09:00, 08:30, 08:00, etc., are overlapping on the left xAxis. The ti ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Promise.all doesn't pause for Firestore queries to iterate

The code I am converting from the Realtime Database to Firestore involves looping through each User (doc) in Firestore and then through each document of 2 nested Subcollections inside each User in order to create some jobs to be handled later. Although I ...

Manipulate Attributes in Javascript

Having an issue here - I'm trying to use JavaScript to set some attributes. for(i=0;i<div_navi.childNodes.length;i++){ if(div_navi.childNodes[i].nodeName =="SPAN"){ div_navi.childNodes[i].setAttribute("onclick","g ...

Can CKEditor be integrated with Mutation Observer? If so, how can this be achieved?

Trying to detect changes in the current CKEditor content. The goal is to identify which element's content has been modified when a user writes multiple paragraphs. Not well-versed in JavaScript or jQuery, but managed to come up with this code after s ...

A guide to accessing JSON values with variables in brightscript

I am having trouble parsing this JSON data using a variable to represent the value. I'm unsure if it's because the variable isn't accurately representing the string or if my approach is incorrect. Function parseCategoriesItems(category As O ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

What is the best way to create a responsive div containing multiple images?

I am working on a slider and my approach is to create a div and insert 4 images inside it. The images will be stacked one above the other using position: absolute, with a width of 1013px, max-width of 100%, and height set to auto for responsiveness. The is ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

Error encountered in Angular after consolidating JavaScript files into a single file: [$injector:modulerr]

After developing an Angular application, everything seemed to be functioning well when I included the controllers.js, routes.js, directives.js files separately in index.html. However, upon attempting to combine these files into a single js file using gul ...

What is the best way to add a listener for a modification of innerHTML within a <span>?

How can I detect changes inside a particular <span> element in order to attach a handler, but so far have been unsuccessful? Below is the HTML snippet: <span class="pad-truck-number-position"><?php echo $_SESSION['truckId']; ?> ...

Ensuring the accuracy of a single field within a form containing multiple fields is made possible through the utilization of

I am facing an issue with my emailValidation method. Even though I want it to run when this.$refs.editUserForm.validate('email') returns true, it always seems to return false, especially when a valid email like <a href="/cdn-cgi/l/email-protec ...

An error has been detected by Internet Explorer 8 at line number 373402504

Internet Explorer 8 is throwing an error message that seems to be from a different galaxy ("Expected identifier, string or number") at a line number that makes no sense. Surprisingly, the code functions perfectly on FireFox. Checking the source code, I se ...

Seamless upward swipe effect (Animation in React Native)

How can I achieve smooth closing of a modal screen by swiping up? The modal screen should be able to close smoothly by swiping up. Currently, the modal is implemented with an Animated Value and PanResponder in order to detect swiping gestures. The problem ...

Creating an in-memory DataTable for testing purposes with Linq: A step-by-step guide

How can a static datatable be created with specific values, like so: Column : col1,col2.....coln Rows : for n number of rows For first row values row11,row12......row1n for second row values row21,row22.....row2n . . . for nth row values rown1,rown2.... ...

Creating dynamic routes for custom locales in Next.js

I'm currently working on a Next.js application with internationalization functionality using next-i18next. Most of my site's pages have been generated in both English and French, except for dynamic routes (like blog/[id]/[blog-title]). For these ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Exploring intricate connections between objects is a feature of Entity Framework

Within my code, I have custom classes called User and Following, with the following structure: public class User : IdentityUser { public User() { Followers = new HashSet<Following>(); Following = new HashSet<Following>( ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...