简体   繁体   中英

How do I pass a List from C# angular to Angular controller?

I'm very new to Angular, and I'm trying to implement it in my .NET MVC application but I've been stumped on how to send data from my C#. In my previous applications, I've used SignalR for all of my client-server communication and I can just return objects seamlessly from server to client without stringifying, serialising, or deserialising.. I presume with Angular it's not that easy? For example, I have server-side methods:

    [HttpGet]
    public int TestInt() { return 42; }

    [HttpGet]
    public string TestString() { return "hooray"; }

    [HttpGet]
    public List<int> TestList() { return new List<int> {0, 1, 2, 3, 4};}

and then in my Angular controller I have the a function that uses $http.get to call these methods

 $http.get('/UserRequest/TestInt').success(function (data) { var x = data; });

 $http.get('/UserRequest/TestString').success(function (data) {var y = data; });

 $http.get('/UserRequest/TestList').success(function (data) {var z = data;});

Now the first two work kinda as expected (though TestInt returns the value as a string, rather than an int), however the last one just returns "System.Collections.Generic.List`1[System.Int32]".

What am I supposed to do to pass a list to angular via $http.get? What if it's my own custom object? Would it be wise to still just use SignalR to get the data, and then use Angular to just call the SignalR methods?

If you're not using WebApi but just plain ASP.NET MVC you may have to do the following

public JsonResult TestList()
{
    return this.Json(new List<int> { 1, 2, 3 });
}

in angularjs controller you have to call angular service in success event you can store the data to scope

    app.controller('mycontroler',['$scope','$http', function($scope,$http){

    $http.get('/UserRequest/TestInt').success(function (data) {


    $scope.data= data; //this scope object we can access in html
    });


}]) 

That's because in ASP.NET MVC when you simple return a type that doens't inherit from ActionResult the framework "stringfies" it by executing the ToString() method.

You can either use a JsonResult (best option) or you can serialize yourself like this:

return Newtonsoft.Json.JsonConvert.SerializeObject(new List<int>() { 2, 3, 4, 5, 5 }) 

(returns a string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM