转换字典以供javascript使用

时间:2015-05-07 08:19:33

标签: c# asp.net asp.net-mvc razor dictionary

我有一个控制器动作,它使用ViewBag将Dictionary传递给视图。

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

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

1 个答案:

答案 0 :(得分:15)

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

@{
   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