如何从MVC控制器填充角度下拉列表?

时间:2015-06-30 07:50:37

标签: angularjs asp.net-mvc

我在mvc控制器中为我获得国家/地区列表的国家/地区提供此信息:

404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

我的问题是如何从angular发送请求以使这些国家进入$ scope,然后在下拉列表中显示它们?

1 个答案:

答案 0 :(得分:0)

创建WebAPI控制器

namespace Example.api
{
    public class ExampleController : ApiController
    {

        ......

        [HttpGet]
        public List<Countries> GetAll()
        {
            return new SelectList(manager.GetCountries(), "Id", "Name");
        }

        ......

    }
}

AngularJS创建service以获取数据:

app.factory('countryFactory', [
    '$http', function($http) {
        var baseAddress = '/Example/';    // path to your controller
        var url;
        return {
            getAll: function() {
                url = baseAddress + 'GetAll/';
                return $http.get(url);
            }
        }
    }
]);

controller

中使用它
app.controller('controllerName', ['$scope', 'countryFactory', function ($scope, countryFactory) {

    ......

    countryFactory.getAll().success(function(data) {
        $scope.countries = data     // this is the $scope variable with `countries` list
    }).error(function() {

    })

    ......

}])