javascript - 将数据从 mvc Controller 传递到 Angular Controller 和范围

标签 javascript asp.net-mvc angularjs

在 MVC Controller 中,我尝试将数据集合传递回 View 。

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);
        }

我通过字符串模型将其发送到 View

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

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

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

此脚本标记驻留在我的 ng-app 内部,因此它在应用程序的范围内,但是当我尝试从 app.controller 引用 if 时,它显示为未定义

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"

有什么想法为什么这个对象没有在 Controller 中被拾取吗?即使我将其定义为依赖项,就好像 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

关于javascript - 将数据从 mvc Controller 传递到 Angular Controller 和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125020/

相关文章:

javascript - 在 do/end block 中禁用 Rails form_for 提交按钮

javascript - 我如何访问另一个 mobx 商店中的 mobx 商店?

javascript - JavaScript 重新路由的 MVC 异常

javascript - 当在另一个模块中的另一个 Controller 上调用函数时,从模块更新 Controller 上的 $scope

javascript - Angularjs $watch 对象数组

javascript - ReactJS 将对象复制到新的状态变量或在树中传递状态

javascript - 有没有办法用我自己的方法压缩javascript?

c# - 在 GridView asp.net 中删除标题样式 css 类

asp.net-mvc - 创建 knockout ViewModel 时使用 Razor 模型出现问题

javascript - 在输入文件类型中选择文件时如何触发按钮单击事件?