我有一个控制器动作,通过使用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" /> @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: "..." }
]
}
为什么重点对象不正确序列化?
可以使用JSON.net将字典序列化为JSON,然后在ViewBag中使用该字符串? – ASG
是的,我可以。我的问题是如何从JavaScript使用它。你能告诉我一个初始样本吗? – Lorenzo
要么或你使用api控制器,并打个电话来获取你的数据... –