0

Within a MVC controller I am trying to pass a collection of data back to the 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); } 

And I send it to the view via a string model

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

Within my cshtml file I am trying to assign the model to a property called mvcData that a part of a service I define

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

This script tag resides inside of my ng-app so its in the scope of the app however when I try to reference if from app.controller it appears as undefined

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

Looking at the model when it is returned to the html I can see that it is a valid object. Using console.log(@Html.Raw(Model) I see objects coming back

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

Any ideas why this object isn't being picked up in the controller? Even though I have it defined as a dependency it's as if the ng-controller doesn't detect it/load it.

    1 Answer 1

    1

    Your dependencies are out of order:

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

    should be

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

    Your current code would mean your searchAttributes.mvcData; is actually referencing timeout.mvcData which is undefined.

    2
    • That was it, man what an oversight on my part. Thanks for catching that
      – rlcrews
      CommentedJun 30, 2015 at 14:09
    • @rlcrews I've done that before and searched for hours before realizing it was so simple of a fix. I felt silly to say the least.
      – KreepN
      CommentedJun 30, 2015 at 14:18

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.