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?
I assume you want to get
x.Value
forvalue
in JSON? Then change your assignment forretValue
toIn 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.