【问题标题】:passing data from mvc controller to angular controller and scope将数据从 mvc 控制器传递到角度控制器和范围
【发布时间】:2015-09-16 11:13:30
【问题描述】:

在 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)); 返回 { mvcData:@Html.Raw(Model) }; });

此脚本标记位于我的 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 没有检测到/加载它。

【问题讨论】:

    标签: javascript asp.net-mvc angularjs


    【解决方案1】:

    你的依赖有问题:

    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

    【讨论】:

    • 就是这样,伙计,这是我的疏忽。感谢您了解
    • @rlcrews 我以前做过,搜索了几个小时才意识到它是如此简单的修复。至少可以说我觉得很傻。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多