c# – 转换字典以供javascript使用
发布时间:2020-12-15 18:31:21 所属栏目:百科 来源:网络整理
导读:我有一个控制器动作,通过使用ViewBag将Dictionary传递给视图. public async TaskActionResult MyAction() { DictionaryATypeViewModel,IEnumerableBTypeViewModel all = await GetDictionary(); ViewBag.MyData = all; return View();} 在视图内部,我需要使
我有一个控制器动作,通过使用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" /> @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,{ BTypeID: 13,{ BTypeID: 14,Description: "..." } ],ATypeViewModel: [ { ServiceTypeID: 21,{ ServiceTypeID: 22,{ ServiceTypeID: 23,{ ServiceTypeID: 24,Description: "..." } ] } 为什么关键对象没有正确序列化? 解决方法
使用一个简单的例子创建一个字典:
@{ 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); }); 控制台输出 更新 根据更新中提供的结构,嵌套循环可以执行此操作,如果结构发生更改,则需要对其进行调整. <script type="text/javascript"> var collection = { ATypeViewModel: [ { BTypeID: 11,Description: "..." } ],BTypeViewModel: [ { ServiceTypeID: 21,Description: "..." } ] } $.each(collection,function (outerKey,outerValue) { $.each(outerValue,value) { $.each(value,function (innerkey,innervalue) { console.log(innerkey); console.log(innervalue); }); }); }); </script> 请注意我需要从您的输出中将您的属性更改为BTypeViewModel. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |