Iterate json data using AngularJS in MVC

I have written an article before on displaying grid in MVC. AngularJS can be one of the ways to do the same. This is not recommended for large records since you have to play around more it for pagination and sorting.

However, if records are not much then this can be useful. One more advantage is that we can make our own template to design the table. Suppose you are consuming data from some services or web APIs then this method will be very useful since we can read that service’s data and iterate through AngularJS.

Here are the steps to iterate JSON data using AngularJS.

Step 1: Create new view page.

public ActionResult AngularJS()
     return View();

Step 2: design your template.

Table design will be simple as normal HTML and CSS. The main point is to note here that we will use ng-repeat directive of angular js for <tr> iteration.

Here is what angularJS doc says about ng-repeat: “The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and the $index is set to the item index or key.”

<div ng-app="myApp" ng-controller="productCtrl">
<table class="table table-bordered">
                <th>Product ID</th>
        <tr ng-repeat="x in products">

Step 3: Add bootstrap CSS, jquery and angularJS library.

<link href="" rel="stylesheet" />

<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="//"></script>

Step 4: Add angularJS script to consume data in JSON format.

<script type="text/javascript">
    var app = angular.module('myApp', []); 
    app.controller('productCtrl', function ($scope, $http) {  
        $http.get('/Home/GetData/').success(function (data) {  
            $scope.products = data;

Step 5: method in a controller to get data.

public class ProductSample
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Department { get; set; }

public ActionResult GetData()
    List products = new List();

    products.Add(new ProductSample() { Id = 1, Name = "Remote Car", Price = 5.2m, Department = "Toys" });
    products.Add(new ProductSample() { Id = 2, Name = "Pen", Price = 1.2m, Department = "Stationary" });
    products.Add(new ProductSample() { Id = 3, Name = "Teddy Bear", Price = 2.2m, Department = "Toys" });
    products.Add(new ProductSample() { Id = 4, Name = "Tennis Boll", Price = 1.2m, Department = "Toys" });

    return Json(products, JsonRequestBehavior.AllowGet);

That’s it. We have done. The output will be as follow.

Let me know what you think.

Leave a Reply

Your email address will not be published. Required fields are marked *