Harry
Harry

Reputation: 3205

Angular and ASP.NET MVC

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>

UPDATEJSON RESULT

Upvotes: 1

Views: 1106

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23230

First replace "Product/Test" with "/Product/Test" notice the "/" at the beginning

Your action will are not implemnted to return a json data but a View (which will be plain HTML) sent to your Angular App.

You must return a Json data in your Test action. Replace the following line:

return View("~/Views/Product/_Test.cshtml");

by this line:

return Json(result.ToList());

You might need to allow GET method with AJAX request then use:

return Json(result.ToList(), JsonRequestBehavior.AllowGet);

Don't forget to add [GET] attribute to your Test action.

You must look at using ASP.Net Web API instead of ASP.Net MVC.

Update 1: Based on the comment below this answer :

Replace linq query by renaming your anonymous type correctly like this :

var result = (from p in db.Products
               select p)
               .Where(x => x.ProductID != 0)
               .Select(a => new
                {
                    productid = a.ProductID,
                    description = a.Description
                });

Notice that there is no upper case into anonymous type properties. You must use it like this because your AngularJS App need it:

<tr>
     <td>{{p.productid}}</td>
     <td>{{p.description}}</td>
</tr>

Update 2: You need to have two actions

  • One that return your view Test
  • another one to get your data TestData

Your Test will look like this:

public ActionResult Test()
{
     return View("~/Views/Product/_Test.cshtml");
}

Your TestData liek this:

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

Finally replace the url of $http.get('Product/Test') with $http.get('/Product/TestData').

Upvotes: 2

Related Questions