Angular,从MVC方法获取数据

时间:2014-08-11 10:03:19

标签: asp.net-mvc angularjs

我知道你可以从div中的角度控制器初始化值,如下所示: 视图:

<div ng-controller="SimpleController">
        <ul>
            <li ng-repeat="cust in customers">
                {{cust.name}} - {{cust.city}}
            </li>
        </ul>
    </div> 

控制器:

function SimpleController($scope) {

        $scope.customers = [
            { name: 'Jane', city: 'New York' },
            { name: 'John', city: 'Chicago', }

        ];
    }

但是,我想说我想从控制器获取数据(可能从数据库中获取数据)并在$scope.customers?中接收其值 看看这个方法:

public ? PassThisToAngular()
        {
            var customer = new List<Customer>()
            {
                new Customer() {Name = "Pauly-D", City = "New Jersey"},
                new Customer() {Name = "Snooki", City = "New Jersey"}
            };


            return ?
        }

我可以从角度控制器调用此方法并将其值存储在@ scope.customers中吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

请检查以下代码,它会对您有所帮助。

在您的脚本方面:

<script>
    var SimpleController = function ($scope, $http) {
    var result = $http.get("/Contact/PassThisToAngular");
    result.success(function (data) {
        $scope.customers = data;
     });
   }
</script>

控制器端:

public string PassThisToAngular()
    {
        var customer = new List<MvcApplication1.Models.Customer>()
        {
            new MvcApplication1.Models.Customer() {Name = "Pauly-D", City = "New
                                                   Jersey"},
            new MvcApplication1.Models.Customer() {Name = "Snooki", City = "New 
                                                   Jersey"}
        };

        var setting = new JsonSerializerSettings{ContractResolver=new 
                              CamelCasePropertyNamesContractResolver()};
        return JsonConvert.SerializeObject(customer, Formatting.None, setting);
    }

答案 1 :(得分:1)

Mvc行动

   public List<Customer> PassThisToAngular()
            {
                var customers = new List<Customer>()
                {
                    new Customer() {Name = "Pauly-D", City = "New Jersey"},
                    new Customer() {Name = "Snooki", City = "New Jersey"}
                };


                return customers 
            }

JS:

function SimpleController($scope, $http) {

$scope.customers =[];

$http.get(/[controller name]/PassThisToAngular).then(function(data){

angular.copy(data,$scope.customers )

}, function(){

alert("Can't get data")

});
    }