2015-05-07 18 views
6

我有一个控制器动作,通过使用ViewBag将字典传递给视图。转换一个字典供javascript使用

public async Task<ActionResult> MyAction() { 
    Dictionary<ATypeViewModel, IEnumerable<BTypeViewModel>> all = await GetDictionary(); 
    ViewBag.MyData = all; 
    return View(); 
} 

在视图内部,我需要使用这个字典创建一个级联单选按钮列表。首先将列出包含像

@{ 
    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" />&nbsp;&nbsp;@entry.Key.Description</label> 
    </div> 
} 

我需要jQuery来创建此代码,但不幸的是我不知道如何转换为用JavaScript来实现的词典中的键值。

编辑:

hutchonoid答案我已经使用Json.NET连载我的字典JSON。

Dictionary<ATypeViewModel, IEnumerable<BTypeViewModel>> list = new Dictionary<ATypeViewModel, IEnumerable<ATypeViewModel>>(); 
[...] 
return await JsonConvert.SerializeObjectAsync(list); 

,然后加在我的javascript代码

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

不幸的是序列化的字符串是不正确的,因为它是在下面的表格

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: "..." } 
    ] 
} 

为什么重点对象不正确序列化?

+2

可以使用JSON.net将字典序列化为JSON,然后在ViewBag中使用该字符串? – ASG

+0

是的,我可以。我的问题是如何从JavaScript使用它。你能告诉我一个初始样本吗? – Lorenzo

+0

要么或你使用api控制器,并打个电话来获取你的数据... –

回答

12

用一个简单的例子创建一个字典:

@{ 
    var services = new Dictionary<string, string> {{"1", "One"},{"2", "Two"}}; 
} 

序列化在你的JavaScript

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

环路它使用每个键和值:

$.each(collection, function (key, value) { 
       console.log(key); 
       console.log(value); 
      }); 

控制台输出

Console output

更新

基于在更新一个嵌套循环会做到这一点,如果结构的变化,但是你需要去适应它提供的结构。

<script type="text/javascript"> 
    var collection = { 
     ATypeViewModel: [ 
      { BTypeID: 11, Description: "..." }, 
      { BTypeID: 12, Description: "..." }, 
      { BTypeID: 13, Description: "..." }, 
      { BTypeID: 14, Description: "..." } 
     ], 
     BTypeViewModel: [ 
      { ServiceTypeID: 21, Description: "..." }, 
      { ServiceTypeID: 22, Description: "..." }, 
      { ServiceTypeID: 23, Description: "..." }, 
      { ServiceTypeID: 24, Description: "..." } 
     ] 
    } 

    $.each(collection, function (outerKey, outerValue) { 

     $.each(outerValue, function (key, value) { 

       $.each(value, function (innerkey, innervalue) { 
        console.log(innerkey); 
        console.log(innervalue); 
       }); 
      }); 

     }); 

</script> 

请注意我需要将您的财产从您的输出更改为BTypeViewModel

+0

感谢您的回答。不幸的是,这不正确。你能看看我的编辑吗? – Lorenzo

+0

@洛伦佐好吧,给我几分钟。 – hutchonoid

+0

@Lorenzo查看我的更新,根据您的数据进行循环。 :) – hutchonoid