Reputation: 97
I have a controller action like this:
List<string> abcd = new List<string>()
foreach (var i in images)
{
abcd.Add("{url:'"+GetImageUrl(i)+"'}");
}
return Json(abcd, JsonRequestBehavior.AllowGet);
So the output of abcd
is
["{url:'/PropertyImage/GetPropertyImage?imageId=1'}", "{url:'/PropertyImage/GetPropertyImage?imageId=2'}", "{url:'/PropertyImage/GetPropertyImage?imageId=8'}"]
But the result I want is:
images:[{url:'/PropertyImage/GetPropertyImage?imageId=1'}, {url:'/PropertyImage/GetPropertyImage?imageId=2'}, {url:'/PropertyImage/GetPropertyImage?imageId=8'}]
In my JavaScript, I have
$.ajax({
type: "GET",
url: url,
success: function (result) {
console.log(JSON.stringify(result));
var data = {
images: [result]
};
template = "{{#images}}<a href='{{url}}'><img class='imageborder' src='{{url}}' style='width:150px;height:150px'></img></a>{{/images}}";
renderedOutput= Mustache.to_html(template,data);
$('#Propertyimagelinks').html(renderedOutput);
}
});
How can I get the correct output?
Upvotes: 0
Views: 84
Reputation: 149000
Rather than trying to manually manipulate JSON strings, it seems a lot simpler to use ASP.NET MVC's built in JSON serialization functionality and a little bit of Linq, like this:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(abcd, JsonRequestBehavior.AllowGet);
And in your JavaScript result handler, use this:
var data = { images: result };
Alternatively you can use this in your controller:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(new { images = abcd }, JsonRequestBehavior.AllowGet);
And in your JavaScript:
var data = result;
Upvotes: 2