c# – 转换字典以供javascript使用

前端之家收集整理的这篇文章主要介绍了c# – 转换字典以供javascript使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个控制器动作,通过使用ViewBag将Dictionary传递给视图.
  1. public async Task<ActionResult> MyAction() {
  2. Dictionary<ATypeviewmodel,IEnumerable<BTypeviewmodel>> all = await GetDictionary();
  3. ViewBag.MyData = all;
  4. return View();
  5. }

在视图内部,我需要使用此字典来创建级联单选按钮列表.第一个列表将包含键值

  1. @{
  2. Dictionary<ATypeviewmodel,IEnumerable<BTypeviewmodel>> services = ViewBag.MyData;
  3. }
  4.  
  5. @foreach ( KeyValuePair<ATypeviewmodel,IEnumerable<BTypeviewmodel>> entry in services ) {
  6. <div class="radio">
  7. <label for="aType"><input type="radio" name="aType" value="@entry.Key.ATypeID" />&nbsp;&nbsp;@entry.Key.Description</label>
  8. </div>
  9. }

我需要jQuery来创建这个代码但不幸的是我不知道如何转换javascript使用的字典.

编辑:

hutchonoid回答之后,我使用Json.NET将我的字典序列化为json.

  1. Dictionary<ATypeviewmodel,IEnumerable<BTypeviewmodel>> list = new Dictionary<ATypeviewmodel,IEnumerable<ATypeviewmodel>>();
  2. [...]
  3. return await JsonConvert.SerializeObjectAsync( list );

然后在我的javascript代码添加

  1. var collection = @Html.Raw( Json.Encode(services) );

遗憾的是,序列化字符串不正确,因为它是以下形式

  1. var collection = {
  2. ATypeviewmodel: [
  3. { BTypeID: 11,Description: "..." },{ BTypeID: 12,{ BTypeID: 13,{ BTypeID: 14,Description: "..." }
  4. ],ATypeviewmodel: [
  5. { ServiceTypeID: 21,{ ServiceTypeID: 22,{ ServiceTypeID: 23,{ ServiceTypeID: 24,Description: "..." }
  6. ]
  7. }

为什么关键对象没有正确序列化?

解决方法

使用一个简单的例子创建一个字典:
  1. @{
  2. var services = new Dictionary<string,string> {{"1","One"},{"2","Two"}};
  3. }

在您的JavaScript中序列化它

  1. var collection = @Html.Raw(Json.Encode(services));

使用键和值使用每个循环它:

  1. $.each(collection,function (key,value) {
  2. console.log(key);
  3. console.log(value);
  4. });

控制台输出

更新

根据更新中提供的结构,嵌套循环可以执行此操作,如果结构发生更改,则需要对其进行调整.

  1. <script type="text/javascript">
  2. var collection = {
  3. ATypeviewmodel: [
  4. { BTypeID: 11,Description: "..." }
  5. ],BTypeviewmodel: [
  6. { ServiceTypeID: 21,Description: "..." }
  7. ]
  8. }
  9.  
  10. $.each(collection,function (outerKey,outerValue) {
  11.  
  12. $.each(outerValue,value) {
  13.  
  14. $.each(value,function (innerkey,innervalue) {
  15. console.log(innerkey);
  16. console.log(innervalue);
  17. });
  18. });
  19.  
  20. });
  21.  
  22. </script>

请注意我需要从您的输出中将您的属性更改为BTypeviewmodel.

猜你在找的C#相关文章