[英]Angular and ASP.NET MVC
我正在学习有角度的东西,并且正在使用ASP.NET MVC5。 我无法通过angular从mvc控制器返回数据。
路由应为localhost / Product / Test,但是在调用angular get方法时,其URL为locahost / Product / Product / Test。 没有任何帮助。
我采取的方法也正确吗? 因为我看过许多教程,其中仅显示如何返回视图。 但是似乎找不到如何返回视图和数据。
MVC控制器
public ActionResult Test()
{
List<Product> products = new List<Product>();
var db = new HotStuffPizzaContext();
var result = (from p in db.Products
select p)
.Where(x => x.ProductID != 0)
.Select(a => new
{
ProductID = a.ProductID,
Description = a.Description
});
return View("~/Views/Product/_Test.cshtml", result);
}
角度应用
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/Test', {
url: '/Product',
templateUrl: '../../Views/Product/_Test.cshtml',
controller: 'testCtrl'
}).otherwise({
redirectTo: '/'
});
}]);
myApp.controller('testCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('Product/Test').success(function (data) {
$scope.products = data;
});
}]);
部分视图
<html data-ng-app="myApp">
<head>
<title></title>
<script src="../../Scripts/angular.min.js"></script>
<script src="../../Scripts/angular-route.js"></script>
<script src="../../Scripts/App/app.js"></script>
</head>
<body data-ng-controller="testCtrl">
<div>
<table class="table table-striped">
<tr data-ng-repeat="p in products">
<th>id</th>
<th>description</th>
</tr>
<tr>
<td>{{p.productid}}</td>
<td>{{p.description}}</td>
</tr>
</table>
</div>
</body>
</html>
索引检视
<h1>INDEX VIEW</h1>
<div data-ng-view=""></div>
<a href="/Product/Test">Test</a>
<script src="../../Scripts/angular.min.js"></script>
<script src="../../Scripts/angular-route.js"></script>
<script src="../../Scripts/App/app.js"></script>
首先将“产品/测试”替换为“ /产品/测试”,并注意开头的“ /”
您的操作将不会执行以返回json数据,而是会发送到Angular App的View(将为纯HTML)。
您必须在Test操作中返回Json数据。 替换以下行:
return View("~/Views/Product/_Test.cshtml");
通过这一行:
return Json(result.ToList());
您可能需要允许GET
方法与AJAX请求一起使用:
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
不要忘记在测试操作中添加[GET]
属性。
您必须考虑使用ASP.Net Web API而不是ASP.Net MVC。
更新1:根据此答案下面的评论:
通过正确重命名您的匿名类型来替换linq查询,如下所示:
var result = (from p in db.Products
select p)
.Where(x => x.ProductID != 0)
.Select(a => new
{
productid = a.ProductID,
description = a.Description
});
请注意,匿名类型属性中没有大写字母。 您必须像这样使用它,因为您的AngularJS应用需要它:
<tr>
<td>{{p.productid}}</td>
<td>{{p.description}}</td>
</tr>
更新2:您需要执行两个操作
您的Test
将如下所示:
public ActionResult Test()
{
return View("~/Views/Product/_Test.cshtml");
}
您的TestData
喜欢:
public ActionResult TestData()
{
List<Product> products = new List<Product>();
var db = new HotStuffPizzaContext();
var result = (from p in db.Products
select p)
.Where(x => x.ProductID != 0)
.Select(a => new
{
productid= a.ProductID,
description = a.Description
});
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}
最后,将$http.get('Product/Test')
的网址替换为$http.get('/Product/TestData')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.