I'm getting an error when I try to retrieve data from a SQL Server database and there is more than 1 table with a foreign key.

Controller:

private DbContext db = new DbContext();

public JsonResult GetAll()
{
        var result = db.Books.ToList();
        return Json(result, JsonRequestBehavior.AllowGet);
}

Service.js:

var Service = {};

Service.getAll = function () {
        return $http.get('BooksModels/GetAll');
};

Controller.js:

getAll();

function getAll() {
    ToshokanService.getAll()

     .success(function (an) {
         $scope.books = an;
         console.log($scope.books);
     })
        .error(function (error) {
            $scope.status = 'Error' + error.message;
            console.log($scope.status);
        });
}

Error: "Errorundefined"

This works when I only have one table in database.

Is it a good idea to retrieve data from a database using AngularJS in ASP.NET MVC?

share
    
What's the error? at where exactly you are getting the error? – Sefa Ümit Oray May 31 '16 at 8:13
    
error: "Errorundefined". On GET localhost/BooksModels/GetAll – VMG May 31 '16 at 8:16
    
So you are having this problem when you have 2 tables in your database? Did you debug your controller? Can you confirm your mvc controller is getting data from database when there are multiple tables? – Sefa Ümit Oray May 31 '16 at 8:20
    
Yes. I get the data in controller. – VMG May 31 '16 at 8:24
    
I'd suggest you debug your MVC controller first, see what's returned in result. – Arthur S. May 31 '16 at 8:27
up vote 1 down vote accepted

If error because table have foreign key, when return Json you should use "select from" like this

 public JsonResult GetLocationJson() {
            var result = (from p in General.DBCtx.Locations.ToList()
                          select new { ID = p.ID, Name = p.Name, Keyword = p.Keyword, Path=p.Path,Des=p.Descript,ParentID=p.ParentID }
                        ).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

There are many way do fix that error but this is the simple way If you don't want to interfere Entity class by Assembly.

share
    
if you want to get data from other table , see in the *** var result = (from p in General.DBCtx.Locations.ToList() select new { ID = p.ID, Name = p.Name, Keyword = p.Keyword, Path=p.Path,Des=p.Descript,ParentID=p.ParentID, ***parent= p.Location1==null?null:new {Id=p.Location1.ID,Name=p.Location1.Name }***, } ).ToList(); – Quỳnh MSO May 31 '16 at 8:38
    
Thank You :D It Works – VMG May 31 '16 at 8:55

Have you tried using then instead of success ? Like so:

ToshokanService.getAll().then(function (an) {
         $scope.books = an;
         console.log($scope.books);
     })

You can read about it here

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.