Reputation: 28859
I am newbie in learning AngularJS. Can anyone help me to understand how to get data from database using angularjs and entity-framework in mvc5.
Let's say we have data table named:
tbl_student {rollno, name}
and we want all the students data from the database. So what should be the most understandable way for new learners.
Angular-Code
var myApp = angular.module("MyModule", []);
myApp.controller("DBcontroller", function ($scope, $http) {
$http.get("AngularController/AllStudents")
.then(function (response) {
$scope.students = response.data
})
})
Html-code in file named "Test.cshtml"
<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>
In MVC Controller
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);
}
}
}
Upvotes: 1
Views: 5051
Reputation: 1
try to change from $http.get
to $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
});
});
Upvotes: -1
Reputation: 1
If you add this in web.config file Http Get will also work
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
</system.web>
</configuration>
Upvotes: 0
Reputation: 5943
The reason why this probably isn't working is because in your get
you are adding the word Controller after Angular.
That is unnecessary.
This should work:
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
})
})
Upvotes: 2