GeekyNuns GeekyNuns - 6 months ago 47
AngularJS Question

Convert c# model to an angular model

I am new to angularjs(started today...) and I have an issue with passing model from c# controller to a controller of angularjs.

It seems that I have to call a get method in my angular controller, to call a c# controller from which I will get json and load it to $scope.people for further manipulations:

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";


Here is my controller :

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

return Json(EmployeeList, JsonRequestBehavior.AllowGet);

As a response I get error code 500;
What is wrong in the request? And could this be made in easier way? May be using my model which is sent to a view from c# controller
@model List<Employee>


So, after some discussions, the solution to the problem seems to be this:

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

Or in other words, creating a Data Transfer Object (DTO) and populating it form EmployeeList

Perhaps there were problems with JSON deserialization.

Glad to help you!