我正在尝试使用JsonResult
获得下面的结果,但我不能
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" }
];
这是我使用的方式:
控制器
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();
}
查看
var localJSON = [ @Html.Raw(ViewBag.AvailableTags)];
结果是
var localJSON = [
{"id":[1,2,3,1553],"label":["tagName1","tagName2","tagName3","tagName1553" ],"value":["tagName1","tagName2","tagName3","tagName1553" ]}
];
我该怎么做才能解决这个问题?
答案 0 :(得分:1)
我假设你想在JSON中获得x.Value
value
?然后将retValue
的作业更改为
var retValue = tagsList.Select(
x => new
{
id = x.Id,
label = x.Name,
value = x.Value
}).ToArray();
在retValue
分配代码中,您创建了一个匿名类型的对象,其中包含数组类型的成员id,label和value。对于您想要的输出,您需要创建一个数组,其中每个成员都是一个具有简单字段id,name和value的对象。