0

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

2 Answers 2

1

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});
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

I get this error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Depends on how you are setting ViewBag.Fleets. You probably need to execute your LINQ expression using ToList() call in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.