title: Convert a Dictionary to be used by javascript
body: <p>I have a controller action which pass a Dictionary to the view by using the ViewBag.</p>
  
  <pre><code>public async Task&lt;ActionResult&gt; MyAction() {
      Dictionary&lt;ATypeViewModel, IEnumerable&lt;BTypeViewModel&gt;&gt; all = await GetDictionary();
      ViewBag.MyData = all;
      return View();
  }
  </code></pre>
  
  <p>Inside the view I need to use this dictionary to create a cascading radio button list. First list would contains the key values like </p>
  
  <pre><code>@{
      Dictionary&lt;ATypeViewModel, IEnumerable&lt;BTypeViewModel&gt;&gt; services = ViewBag.MyData;
  }
  
  @foreach ( KeyValuePair&lt;ATypeViewModel, IEnumerable&lt;BTypeViewModel&gt;&gt; entry in services ) {
      &lt;div class="radio"&gt;
          &lt;label for="aType"&gt;&lt;input type="radio" name="aType" value="@entry.Key.ATypeID" /&gt;&amp;nbsp;&amp;nbsp;@entry.Key.Description&lt;/label&gt;
      &lt;/div&gt;
  }
  </code></pre>
  
  <p>I need jQuery to create this code but unfortunately I dont know how to convert the dictionary to be used by javascript.</p>
  
  <p>EDIT:</p>
  
  <p>Following <a href="https://stackoverflow.com/a/30095722/431537">hutchonoid</a> answer I have serialized my dictionary to json by using Json.NET.</p>
  
  <pre><code>Dictionary&lt;ATypeViewModel, IEnumerable&lt;BTypeViewModel&gt;&gt; list = new Dictionary&lt;ATypeViewModel, IEnumerable&lt;ATypeViewModel&gt;&gt;();
  [...]
  return await JsonConvert.SerializeObjectAsync( list );
  </code></pre>
  
  <p>and then added it in my javascript code</p>
  
  <pre><code>var collection = @Html.Raw( Json.Encode(services) );
  </code></pre>
  
  <p>unfortunately the serialized string is not correct as it is in the following form</p>
  
  <pre><code>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: "..." }
      ]
  }
  </code></pre>
  
  <p>Why do the key object does not get serialized correctly?</p>