pato.llaguno
pato.llaguno

Reputation: 741

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

Upvotes: 0

Views: 424

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

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

Upvotes: 1

Shyju
Shyju

Reputation: 218962

You can serialize it like this.

SerializeObject method returns a string which is the json string representation of your C# object.

var fleetsArray= @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Fleets))
console.log(fleetsArray);

Upvotes: 0

Related Questions