VMG VMG - 6 months ago 85
AngularJS Question

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?

Answer

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.

Comments