Passing Json from action to view by ViewBag

送分小仙女□ 提交于 2019-12-08 12:33:22

问题


I'm trying to get the result below using JsonResult, but I can't

var localJSON = [

            { "id": "1", "label": "tagName1", "value": "tagValue1" },
                { "id": "2", "label": "tagName2", "value": "tagValue2" },
                { "id": "3", "label": "tagName3", "value": "tagValue3" },
                { "id": "1553", "label": "tagName1553", "value": "tagValue1553" }
    ];

Here is the way I use:

controller

private JsonResult GetAvailableTags()
        {
            var tagsList = Facade.Tags.Get(CurrentLocale.ID);
            var retValue = new
            {
                id = tagsList.Select(x => x.ID).ToArray(),
                label = tagsList.Select(x => x.Name).ToArray(),
                value = tagsList.Select(x => x.Name).ToArray()
            };
            return Json(retValue);
        }
public ActionResult AddPhoto()
        {

            var availblableTags = GetAvailableTags();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            ViewBag.AvailableTags = serializer.Serialize(availblableTags.Data);
            return View();
        }

view

var localJSON = [ @Html.Raw(ViewBag.AvailableTags)];

The result is

var localJSON = [
   {"id":[1,2,3,1553],"label":["tagName1","tagName2","tagName3","tagName1553" ],"value":["tagName1","tagName2","tagName3","tagName1553" ]}
        ];

What should I do to resolve that?


回答1:


I assume you want to get x.Value for value in JSON? Then change your assignment for retValue to

var retValue = tagsList.Select(
    x => new 
    { 
        id = x.Id, 
        label = x.Name, 
        value = x.Value 
    }).ToArray();

In your retValue assignment code you were creating a single object of anonymous type with array-typed members id, label and value. For the output you want you need to create an array, each member of which is an object with simple fields id, name and value.



来源:https://stackoverflow.com/questions/8427635/passing-json-from-action-to-view-by-viewbag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!