【发布时间】:2016-02-12 19:49:28
【问题描述】:
我正在学习 Angular,我正在使用 ASP.NET MVC5。我无法通过角度从 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);
}
Angular 应用
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>
【问题讨论】:
-
尝试将 /Product 从您的索引视图中的链接中删除。
-
您的控制器名称是什么? (包含您的测试操作的类。
-
@RickestRick 我在“/”应用程序中收到以下服务器错误。网址是localhost:14634/Test
-
@CodeNotFound 产品控制器
-
在 $http.get('Product/Test') 中。
标签: c# asp.net angularjs asp.net-mvc