Ahmad Shli
Ahmad Shli

Reputation: 69

Read the returned JSON data from MVC controller in Angular controller

I am very new to AngularJS, please accept my apology if this is an easy question. I also hope that the title of the question is understandable?

I am using AngularJS with ASP.Net MVC application to ready data from SQL server table and then display the data on the view. Everything looks fine but when I try to step forward for more advanced tasks, I find out that I am not able to read the object from Angular module.

For example, I want to read the contact details of a user, each user has different number of contacts. So, the ng-repear limitTo should not be the same. To do that, I wanted to read some data and then set a variable to the number of items that I found on the database and then use that variable in my ng-repear limitTo

This is part of my view:

<table>
<tr ng-repeat="contact in users | limitTo:loopVar">
    <td>
        <div ng-show="!contactsElements" class="item_list">{{contact.contacts + " (" + contact.contactDesc + ")"}}</div>
    </td>
</tr>

Where loopView is the variable that I want to use

This is the Angular module/controller:

var myApp = angular.module('myApp', []);

myApp.controller('mainController', function ($scope, $http) {
$http.get('/Home/GetUser')
    .success(function (result) {
        $scope.users = result;
    })
    .error(function (data) {
        console.log(data);
    });

\\HOW I CAN SET THE loopVar HERE SO I CAN USE IT IN MY VIEW??
}

The MVC controller is below:

public JsonResult GetUser()
    {
        User userData = (User)Session["user"];            
        var db = new testDBEntities();
        return this.Json((from userObj in db.Users
                          join uc in db.UserContacts
                          on userObj.Id equals uc.usrID
                          join us in db.Users
                          on userObj.usrSupervisor equals us.Id
                          where userObj.Id.Equals(userData.Id)
                          select new
                          {
                              Id = userObj.Id,
                              usrNme = userObj.usrNme,
                              fName = userObj.usrFirstName,
                              lName = userObj.usrLastName,
                              ssno = userObj.usrSSN,
                              contacts = uc.usrContact,
                              contactDesc = uc.usrContactDescription,
                          })
                          , JsonRequestBehavior.AllowGet
                        );
    }

I hope you understand my point... In general, how I can read the returned JSON object in my Angular controller before using it in my view? As you can see, I am able to read data in my view by using ng-repeat directive but I don't know how to ready individual field in my Angular controller.

Thank you

Upvotes: 1

Views: 7228

Answers (1)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16846

The data object returned is formated the way you specified it in your controllers JsonResult.

To get each in the array passed from your controllers GetUser function

$http.get('/Home/GetUser')
    .success(function (result) {
        $scope.users = result;

        //Loop the json
        if (result != null) {
            for (var i = 0; i < result.length; i++) {

                //Then you get the values like this

                //result[i].Id; 
                //result[i].usrNme; 
                //result[i].fName; 
                //result[i].lName; 
                //result[i].ssno; 
                //result[i].contacts; 
                //result[i].contactDesc; 

                }
        }

    })
    .error(function (data) {
        console.log(data);
    });

If you just want to send one value from the controller into a JsonResult you can do it like this

Let's say you have a method call GetLoopVar() in your controller:

public JsonResult GetLoopVar()
{
    string loopVar = "Im a var";
    return Json(loopVar, JsonRequestBehavior.AllowGet)
}

And in your client

$http.get('/Home/GetLoopVar')
    .success(function (result) {

        $scope.loopVar = result;

        //$scope.loopVar = "Im a var"

    })
    .error(function (data) {
        console.log(data);
    }); 

To combine the two and achieve the objective here I would first make sure that the scope value is set that is used in the filter. After the loopVar is set then get the users. One way to do that is by calling the getUsers function after you have set the loopVar value like this

myApp.controller('mainController', function ($scope, $http) {

    $scope.getLoopVar = function(){
        $http.get('/Home/GetLoopVar')
            .success(function (result) {
                $scope.loopVar = result;

                //Call get user function
                $scope.getUsers();
            })
            .error(function (data) {
                console.log(data);
            });
    };

    $scope.getUsers = function(){
        $http.get('/Home/GetUser')
            .success(function (result) {
                $scope.users = result;
            })
            .error(function (data) {
                console.log(data);
            });
    };

    //To get the values on load, call the $scope.getLoopVar() in the controller
    $scope.getLoopVar();
}

Upvotes: 1

Related Questions