繁体   English   中英

将数据从MVC控制器传递到角度控制器和示波器

[英]passing data from mvc controller to angular controller and scope

在MVC控制器中,我试图将数据集合传递回视图。

private string GetEntityList()
        {
            var entities = new[]
            {
               new EntityList{ EntityId = 1, EntityName = "Entity 1"},
               new EntityList{ EntityId = 2, EntityName = "Entity 2"},
               new EntityList{ EntityId = 3, EntityName = "Entity 3"},
               new EntityList{ EntityId = 4, EntityName = "Entity 4"},
               new EntityList{ EntityId = 5, EntityName = "Entity 5"}
            };

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            return JsonConvert.SerializeObject(entities, Formatting.None, settings);
        }

然后通过字符串模型将其发送到视图

public ViewResult Index()
{
    return View("index","", GetEntityList());
}

在我的cshtml文件中,我试图将模型分配给名为mvcData的属性,该属性是我定义的服务的一部分

    app.factory("searchAttributes", function() {
        console.log(@Html.Raw(Model));
        return { mvcData:@Html.Raw(Model) };

    });

</script>

这个脚本标签位于我的ng-app内部,因此它位于应用程序的范围内,但是当我尝试从app.controller引用时,它似乎未定义

app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, searchAttributes, ngNotifier, $log, $timeout) {

    var vm = this;
    //bootstraped data from MVC
    $scope.searchAttributes = searchAttributes.mvcData;

}]);

查看返回到html的模型,我可以看到它是一个有效的对象。 使用console.log(@Html.Raw(Model)我看到对象回来了

 Object[0] entityId: 1   entityName: "Entity 1"
 Object[1] entityId: 2   entityName: "Entity 2"

有什么想法为什么不在控制器中拾取此对象? 即使我已将其定义为依赖项,也就好像ng-controller不会检测到/加载它。

谢谢你

您的依存关系不正常:

app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, searchAttributes, ngNotifier, $log, $timeout) {

应该

app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, ngNotifier, $log, $timeout, searchAttributes) {

您当前的代码将表示您的searchAttributes.mvcData; 实际上是引用timeout.mvcData ,它是未定义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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