如何使用mvc中的angularjs和实体框架从db获取数据

时间:2016-06-22 12:19:59

标签: angularjs asp.net-mvc entity-framework asp.net-mvc-5

我是学习AngularJS的新手。任何人都可以帮助我理解如何使用mvc5中的angularjs和entity-framework从数据库中获取数据。

假设我们有一个名为“tbl_student {rollno, name}”的数据表,我们希望所有学生都能从数据库中获取数据。那么对于新学习者来说应该是最容易理解的方式。

角码

var myApp = angular.module("MyModule", []);
myApp.controller("DBcontroller", function ($scope, $http) {
$http.get("AngularController/AllStudents")
    .then(function (response) {
        $scope.students = response.data
    })
})

名为“Test.cshtml”的文件中的Html代码

<body  ng-app="MyModule">
<table ng-controller="DBcontroller">
     <thead>
          <tr>
             <th>Name</th>
             <th>City</th>
             <th>Institute</th>
           </tr>
     </thead>
           <tr ng-repeat="student in students">
             <td>{{ student.Name }}</td>
             <td>{{ student.City }}</td>
             <td>{{ student.Institute }}</td>
          </tr>
 </table>
 </body>

在MVC控制器中

public class AngularController : Controller
{
    // GET: Angular
    public ActionResult Test()
    {
        return View();
    }

    public JsonResult AllStudents()
    {
        using (EducationContext context = new EducationContext())
        {
            var students = context.tbl_Student.ToList();
            return Json(students, JsonRequestBehavior.AllowGet);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

这可能不起作用的原因是因为在get中您在 Angular 之后添加了 Controller 这个词。

这是不必要的。

这应该有效:

var myApp = angular.module('MyModule', []);
    myApp.controller('DBcontroller', function ($scope, $http) {
    $http.get('/Angular/AllStudents') // added an '/' along with deleting Controller portion
        .then(function (response) {
            $scope.students = response.data
        })
    })

答案 1 :(得分:0)

如果你在web.config文件中添加它,Http Get也将起作用

<configuration>
  <system.web>
    <webServices>
      <protocols>
       <add name="HttpGet"/>
      </protocols>
    </webServices>
  </system.web>
</configuration> 

答案 2 :(得分:-1)

尝试从$http.get更改为$http.post

var myApp = angular.module('MyModule', []);
myApp.controller('DBcontroller', function ($scope, $http) {
    $http.post('/Angular/AllStudents') // added an '/' along with deleting Controller portion
    .then(function (response) {
        $scope.students = response.data
    });

});