I am learning angular, and I am using ASP.NET MVC5. I am unable to return data from mvc controller via angular.

The route should be localhost/Product/Test, but when angular get method is calling it the url is locahost/Product/Product/Test. Any help is appreacited.

Is the approach I have taken correct also? Because I have seen many tutorials where they show how to return a view only. But cannot seem to find how to return a view and data.

Screenshot Screen Shot

MVC controller

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 app

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;
      });
  }]);

Partial View

<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>

Index View

<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>

Related posts

Recent Viewed