VMG
VMG

Reputation: 135

ASP.NET MVC - get data from SQL Server with angularJS

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?

Upvotes: 0

Views: 1824

Answers (2)

Quỳnh MSO
Quỳnh MSO

Reputation: 66

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.

Upvotes: 2

Arthur S.
Arthur S.

Reputation: 202

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

Upvotes: 0

Related Questions