VMG VMG - 2 years ago 197
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.


private DbContext db = new DbContext();

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


var Service = {};

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



function getAll() {

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

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download