2016-05-31 25 views
0

當我試圖從SQL Server數據庫中檢索數據並且存在多個具有外鍵的表時,出現錯誤。ASP.NET MVC - 使用angularJS從SQL Server獲取數據

控制器:

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

錯誤: 「Errorundefined」

這工作時,我只有數據庫中有一張表。

在ASP.NET MVC中使用AngularJS從數據庫檢索數據是一個好主意嗎?

+0

有什麼錯誤?你到底在哪裏得到錯誤? – Sefa

+0

錯誤:「Errorundefined」。在GET http:// localhost/BooksModels/GetAll – VMG

+0

因此,當數據庫中有兩個表時,您遇到了這個問題?你有沒有調試你的控制器?如果有多個表,你能確認你的mvc控制器從數據庫中獲取數據嗎? – Sefa

回答

1

如果錯誤,因爲表有外鍵,當返回JSON你應該使用這樣

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

有很多方式做修復的錯誤「從選擇」,但是這是一個簡單的方法如果不這樣做想要通過Assembly來干涉實體類。

+0

,如果您想從其他表中獲取數據,請參閱*** 'var result =(從General.DBCtx.Locations.ToList()中的p獲取() 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();' –

+0

Thank You:D It Works – VMG

0

您是否嘗試過使用then而不是success?像這樣:

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

你可以閱讀一下here