我正在尝试使用带有角度js的asp.mvc从数据库中获取记录,但我无法获取记录。
我有员工表
员工控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SelectData.Models;
namespace SelectData.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
return View();
}
public ActionResult getAll()
{
using (EmployeeDBEntities dbContext = new EmployeeDBEntities())
{
var employeeList = dbContext.Employees.ToList();
return View(employeeList);
}
}
}
}
Angular JS模块
var app = angular.module("AngularApp", []);
Angular JS服务
app.service("EmployeeService", function ($http) {
this.getEmployee = function () {
debugger;
return $http.get("/employee/getAll");
};
});
Angular JS Controller
app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();
function GetAllEmployee() {
debugger;
var getAllEmployee = EmployeeService.getEmployee();
getAllEmployee.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Data not found');
});
}
});
查看
@{
ViewBag.Title = "getAll";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-controller="EmpCtrl">
<div>
<h2 align="center">Angular JS Basic Example</h2>
<h5 align="center">Employee List</h5>
<table border="1" cellpadding="10" align="center">
<tr>
<td>
Employee Id
</td>
<td>
First Name
</td>
<td>
Address
</td>
</tr>
<tr ng-repeat="emp in employees">
<td>
{{emp.EmpId}}
</td>
<td>
{{emp.FirstName}}
</td>
<td>
{{emp.LastName}}
</td>
</tr>
</table>
</div>
</div>
_Layout.cshtml
<!DOCTYPE html>
<html ng-app="AngularApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="~/Content/angular/Module.js"></script>
<script src="~/Content/angular/Service.js"></script>
<script src="~/Content/angular/Controller.js"></script> @Styles.Render("~/Content/css")
</head>
<body>
@RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false)
</body>
</html>
数据未在浏览器中显示,但在浏览器上显示为json格式。请建议
答案 0 :(得分:1)
您的getAll
操作方法返回的视图结果基本上是html标记(字符串)。您应该返回表示数据的json数组。数组中的每个项目都应包含EmpId
,FirstName
和LastName
属性..
public ActionResult getAll()
{
using (var db = new EmployeeDBEntities())
{
var employeeList = db.Employees.Select(f=>new { EmpId =f.EmpId ,
FirstName = f.FirstName,
LastName = f.LastName }
).ToList();
return Json(employeeList,JsonRequestBehavior.AllowGet);
}
}
这里我将Employee项目投射到一个匿名对象。因此getAll
的结果将是json数组,如。
[
{
"EmpId": 1,
"FirstName": "Shyju",
"FirstName": "K"
}
]
您的角度代码可以用于ng-repeat
getAll.cshtml
除外),您应该尝试在浏览器中访问该操作方法(可能是索引视图?)