Search code examples
javascriptarraysasp.net-mvcviewbag

Create a Javascript object with Viewbag data


I need to create an object to send to a funciton in javascript but this information is coming from my viewbag.

new FleetSelector("False",
[{"OwnerId": "2df3893d-c406-48fe-8443-1622ddc51af2", "DisplayName": "String 1" }, 
{ "OwnerId": "7A402CD7-5EEA-4AF5-80A3-22EED0610C9D", "DisplayName": "String 2" }]);

Inside my viewBag i have a Fleets model List that has a Guid OwnerId and a String ownerName, this is something i tried, which i know it's wrong but ill add it to try and explain what I'm hoping to achieve

new FleetSelector("False",
                    [ @foreach (var fleet in ViewBag.Fleets)
                    {
                        '{' + '"' + "OwnerId" + '"' + ':' + '"' + fleet.OwnerId + '"' + ',' + '"' + "DisplayName" + '"' + ':' + '"' + fleet.ownerName + '"' + '}'
                    }  }]);

Solution

  • You have to populate array outside of the FleetSelector object.

    new FleetSelector("False",array);
    

    Here is array definition:

    var array=[];
    @foreach (var fleet in ViewBag.Fleets)
    {
       @:array.push({"OwnerId":@fleet.OwnerId,"DisplayName":@fleet.ownerName});
    }