簡體   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