Transform a C# model into an Angular model

I'm just starting out with angularjs (started today...) and I'm having trouble passing a model from my c# controller to an angularjs controller.

It appears that I need to call a get method in my angular controller to fetch data from the c# controller which will return json for me to load into $scope.people for further manipulation:

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, $http) {

        $http({url: "/Home/GetPersons",method: "GET"
            }).success(function (data) {
                $scope.people = data;
            }).error(function (error) {
                $scope.error = "Failed to load";
        });

     });
</script>

This is my controller :

  [HttpGet]
    public JsonResult GetPersons()
    {
        using (HRMEntities db = new HRMEntities())
        {
            var EmployeeList = db.Employees.Where(e => e.EmployeeId >= 0).ToList();

            return Json(EmployeeList, JsonRequestBehavior.AllowGet);
        }
    }

When I make the request, I receive error code 500; What am I doing wrong in the request? Is there an easier way to do this? Maybe utilizing the model passed to the view from the c# controller @model List<Employee>

Answer №1

After some deliberation, it appears that the solution to the issue is as follows:

return Json(EmployeeList.Select(x=>new {Name=x.Name }), JsonRequestBehavior.AllowGet)

In simpler terms, the recommendation is to create a Data Transfer Object (DTO) and populate it from EmployeeList

Possibly, there were complications with JSON deserialization.

I'm pleased to have been of assistance!

Answer №2

While I may be arriving a bit tardy to the party, our team developed an incredibly useful tool at our organization. We crafted models that seamlessly correlate from C# to JavaScript (vanilla), and we even incorporated AngularJS factory model wrappers to enhance Domain Model functionality.

Check out our creation on GitHub!

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

Setting the default selected option in Vue for an object

Can the v-model data be different from the default option in this scenario? data: function() { return { user: { usertype: {}, } } <select v-model="user.usertype" class="btn btn-secondary d-flex header-input"> <option v-for= ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

What is the best way to verify if a value matches the container ID in Vue?

I am trying to create a condition where a property is checked against the ID of a div container. If they match, I want to display the container. For example, in the code snippet below, I need to compare the activeWindow property with the div id. If they a ...

Showing a loading animation inside an HTML element

I have a main webpage that contains several buttons. Each button, when clicked, loads a specific target page as an object within a div on the main page. The "target" refers to the page that will be displayed within the object. <script> .... chec ...

Implementing server-side middleware for individual routes in Next.js

I am currently exploring options for executing code upon the initial page load of each request. My goal is to determine the domain of the request and redirect to a specific section of the website based on this information. One possibility I have considere ...

Tips for ensuring the button click function works properly following the execution of ajax in Selenium

I am facing an issue where I cannot consistently get the button to be clicked, even though it works rarely. Despite using waits such as: WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.ElementToBeCli ...

Rendering images in Next.js version 10

Just recently, Next.js version 10 was launched featuring the latest Image element, making it a great asset for websites that heavily rely on images! When I receive an HTML response from the server, it looks something like this: HTML = "<div> &l ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

export default interpretation of something()

While browsing through the React Navigation documentation, I came across the following code snippet: import Ionicons from 'react-native-vector-icons/Ionicons'; import { createBottomTabNavigator } from 'react-navigation'; export defaul ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

My AngularJS integrated with Spring MVC is failing to render the desired page

Hello everyone, I'm fairly new to AngularJS and Spring MVC. I've managed to set up a basic application, but unfortunately, when I try to load it, nothing appears on the screen. The console shows a 404 error. I've double-checked everything, b ...

Updating parent data when new data is added in child component in React

I'm just starting to learn React and I've been reading a lot about updating children components when the parent component is updated, but I haven't come across much information about the opposite scenario. Currently, I have a parent compone ...

The Laravel view is displaying on Chrome dev-tools instead of redirecting to the blade template

Hello amazing developers at stackoverflow, I'm currently working on a project focused on campaign management. The goal is to enable users to create, edit, and preview their campaigns before publishing them. To achieve this, I am utilizing MySQL and F ...

The ng-model in AngularJS is experiencing issues with two-way binding within a directive

Seeking to develop a straightforward Angular directive for handling currency input. The objective is to have it operate as a float in the model while showing two decimal places to the user. The code implemented for this purpose is as follows: // Currenc ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

External code is causing issues with hitting breakpoints in struct constructors

In my observation, I have come across an interesting behavior when calling the GetEnumerator method of System.Array: var array = new int[] { 1, 2, 3, 4 }; var arrayEnumerator = array.GetEnumerator(); arrayEnumerator.MoveNext(); A similar situa ...

changing font size on a mobile-friendly site using javascript

Currently, I am designing a responsive webpage utilizing Bootstrap framework. Situated in the center of the screen is a text that reads: <p id="entershop" ><a class=no-deco href="shop.html">enter shop</a></p> Within the Bootstra ...

Effortlessly generate various socket.io events within a node.js environment

Seeking advice on optimizing and following the DRY principle. My node server is functioning correctly, but I want to streamline the code for future developers. Currently, I have a series of events being set up in this manner: var debug = true; io.sock ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...