Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

Here 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);
        }
    }

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>

like image 563
GeekyNuns Avatar asked May 15 '26 04:05

GeekyNuns


1 Answers

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!

like image 52
Alex Avatar answered May 16 '26 19:05

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!