I have a controller action that passes a dictionary to a view using a ViewBag.
public async Task<ActionResult> MyAction() { Dictionary<ATypeViewModel, IEnumerable<BTypeViewModel>> all = await GetDictionary(); ViewBag.MyData = all; return View(); }
Inside the view, I need to use this dictionary to create a list of cascading switches. The first list contains key values ββsuch as
@{ Dictionary<ATypeViewModel, IEnumerable<BTypeViewModel>> services = ViewBag.MyData; } @foreach ( KeyValuePair<ATypeViewModel, IEnumerable<BTypeViewModel>> entry in services ) { <div class="radio"> <label for="aType"><input type="radio" name="aType" value="@entry.Key.ATypeID" /> @entry.Key.Description</label> </div> }
I need jQuery to create this code, but unfortunately I don't know how to convert the dictionary that javascript will use.
EDIT:
Following hutchonoid answer I am serializing my dictionary to json using Json.NET.
Dictionary<ATypeViewModel, IEnumerable<BTypeViewModel>> list = new Dictionary<ATypeViewModel, IEnumerable<ATypeViewModel>>(); [...] return await JsonConvert.SerializeObjectAsync( list );
and then added it to my javascript code
var collection = @Html.Raw( Json.Encode(services) );
Unfortunately, the serialized string is incorrect because it is in the following form
var collection = { ATypeViewModel: [ { BTypeID: 11, Description: "..." }, { BTypeID: 12, Description: "..." }, { BTypeID: 13, Description: "..." }, { BTypeID: 14, Description: "..." } ], ATypeViewModel: [ { ServiceTypeID: 21, Description: "..." }, { ServiceTypeID: 22, Description: "..." }, { ServiceTypeID: 23, Description: "..." }, { ServiceTypeID: 24, Description: "..." } ] }
Why doesn't the key object get serialized correctly?