How can I structure a class in .Net to send a JSON key-value pair to Angular?

I'm currently trying to implement an Angular keyvaluepair and my goal is to pass the following data structure to my Angular type lawyers: { [key: number]: string };

{2: 'foo', 1: 'bar'};

Once processed in the controller, I need to send this data back to the user interface.

Below is a snippet of my controller:

    [HttpGet("check/{matter}")]
    public async Task<IActionResult> SearchMatter(string matter)
    {
        var exists = await _cmpRepo.CheckMatter(matter);

        if (!exists)
            return BadRequest("error");

        var claims = await _autoRepo.GetClaimsByMatter(matter);

        var attorneys = await _autoRepo.GetAttorneys();

        return Ok(new ClaimInfo { Names = claims, Attorneys = attorneys });
    }

Here's a glimpse at the code for ClaimInfo.cs

public class ClaimInfo
{
    public IEnumerable<string> Names { get; set; }
    public IEnumerable<KeyValuePair<int, string>> Attorneys { get; set; }
}

Answer №1

Check out this functional demo in .ts format

 keyVal = {
    1: "foo",
    2: "chanaka",
  };

The .html file includes:

<div *ngFor="let item of keyVal | keyvalue">
      {{item.key}}:{{item.value}}
</div>

Answer №2

I successfully eliminated the "" by following these steps: converting the string into an object with JSON.parse()

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

Navigate to a specific action while passing a reference type

I created a custom type called Filter: public class Filter { public int FilterId { get; set; } public ICollection<int> ModuleIds { get; set; } } Now, I need to redirect to an action and pass an instance of this type: public ActionResult Nav ...

The Formly form is experiencing a glitch where it does not reflect the updated default value of

My goal is to dynamically update the Formly form rendering based on changes made in the form scheme (which consists of an array of FormlyFormConfig objects). I have noticed that the updating works when adding a new object or modifying a field label, but it ...

There is a Typescript error stating that the argument of type 'NodeListOf<HTMLInputElement> | undefined' cannot be assigned to the parameter of type 'Iterable<HTMLInputElement> ...'

While working on my React/Typescript App, I encountered an issue when trying to access an array of inputs in an event listener using 'e.currentTarget'. To solve this, I utilized Array.from() to convert the NodeListOf into an array and ensured tha ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

Custom button click changes page state on browser's back button press

After selecting filters and clicking the search button on the first page, users navigate to a second page where they interact with a grid. Now, in order to return to the first page with just one click (without using the browser back button), I need to ensu ...

The mat-autocomplete feature is sending multiple requests to the server instead of just one

After inputting a few characters, my code is designed to make a GET request and auto-complete the returned JSON object. However, I noticed that even after stopping typing for a few seconds, the backend is being hit multiple times rather than just once (I h ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

A factory pattern for Typescript modules

In the world of Node.js, one popular method is to utilize the module factory pattern. Let's take a look at an example: m.js function factoryMethod(module) { // perform some actions and return object initialized with module parameter } app.js var ...

What is the best way to execute a function that retrieves data from a MySQL query and then sends it back as a result in Express.js?

How can I refactor my code to efficiently call a function that returns the result of a MySQL query and send it back in an Express.js response? I am attempting to streamline my SQL queries by exporting them into individual functions to eliminate duplicatio ...

Retrieve the value of an object without relying on hardcoded index values in TypeScript

I am working with an object structure retrieved from an API response. I need to extract various attributes from the data, which is nested within another object. Can someone assist me in achieving this in a cleaner way without relying on hardcoded indices? ...

Guide on linking JSON keys to properties of a class

I have received a JSON response as shown below: { "Robert": [ { "id": "123", "class": "7th", "lastname": "johnson" } ], "William": [ { "id": "124", "class": "7th", "lastname": "parker" } ] } I am l ...

Bootstrap navbar does not collapse when clicking and is experiencing a responsiveness problem

Struggling to hide the navbar on my responsive site. Button click doesn't always close the navbar as intended. If anyone can assist, I'm working on an Angular 9 project. Demo : index.html : <!doctype html> <html lang="en"> <he ...

Encountering a Node V18 Peer Dependency Conflict错

Can someone please help me understand what's causing this error? Every time I try to install a dependency, this keeps popping up. I'm completely lost and unsure of what's happening. npm ERR! 1 more (the root project) npm ERR! peer ...

What is the best way to find the lengths of strings within an array?

How can I output strings of a certain length from an array in C# using ASP.NET? string[] myArray = {"stringone", "stringtwo", "stringthree"}; I attempted this: foreach (thing in myArray) { if(thing.Length < 10) { // do something } } @ ...

Sending duplicate requests occurs when intercepting HTTP responses

Upon observation, it has been noted that there is a duplicate triggering of the request when intercepting HTTP response and using subscribe to retrieve the value in the Observable response. Below is the code snippet: Intercepting Http Request and Respons ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

Using the ngrx signalStore within the facade design pattern - a step-by-step guide

How can I utilize ngrx's new signalStore in Angular to fetch locations of arms, save them in the state, and replace a service with LOCATION_STORE after setting the locations on a map with markers? The challenge lies in waiting for the response of loca ...

What is the optimal approach for implementing language translation in Angular 2?

I have a JSON file that contains translations of each word into 5 different languages. These translations are specifically for words used across the entire site, so I do not require any additional libraries or plugins to manage translations. What would be ...

Find all words using Regex, but make sure to exclude certain matches

I need a regular expression that can search through multiple strings and identify specific words within them: Maces Armour Evasion Shields However, I want to exclude any strings that contain these words: Swords Axes Staves For example, the following st ...

Using LINQ extension methods to left outer join and group by count

I have two databases called Categories and Ads. Each Category can be associated with multiple ads in the Ads table. My goal is to retrieve all category details along with the number of ads they each contain. The Linq expression I am currently using only ...