我正在學習角度,而我正在使用ASP.NET MVC5。我無法通過角度從mvc控制器返回數據。Angular和ASP.NET MVC
路由應該是localhost/Product/Test,但是當角度get方法調用它時,url是locahost/Product/Product/Test。任何幫助appreacited。
我採取的方法也正確嗎?因爲我看過很多教程,他們只展示瞭如何返回視圖。但似乎無法找到如何返回視圖和數據。
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>
嘗試從索引視圖中的鏈接中拿取/產品。 –
你的控制器名稱是什麼? (包含您的測試操作的類 – CodeNotFound
@RickestRick在'/'應用程序中,我得到以下服務器錯誤,並且URL是http:// localhost:14634 /測試 – Haris