I'm struggling with multiple image uploads in redactor. Specifically, creating the return JSON after uploading and saving the images.
I have managed to do it using StringBuilder
, but i would like to do it in a properly typed class if possible, using return Json(redactorResult, JsonRequestBehavior.AllowGet);
Desired Format
From the redactor demo page, I can see the formatting I require is:
{
"file-0": {
"url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg",
" id":"70e8f28f4ce4a338e12693e478185961"
},
"file-1":{
"url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg",
"id":"456d9b652c72a262307e0108f91528a7"
}
}
C# Class
But to create this JSON from a c# class I think I would need something like this :
public class RedactorFileResult
{
public string url {get;set;}
public string id {get;set;}
}
public class RedactorResult
{
public RedactorFileResult file-1 {get;set;}
public RedactorFileResult file-2 {get;set;}
// .. another property for each file...
}
... which seems impossible at worst (never know how many images will be uploaded), and a bit impractical at best.
Question
Am I approaching this correctly? Is there a way to do this that I'm not aware of?
Or am I better just sticking with string builder on this occasion?
Define a class for single item:
public class File
{
public string Url { get; set; }
public string Id { get; set; }
}
Then create your files like this:
var files = new List<File>();
files.Add(new File{Url = "tmp/abc.jpg", Id = "42"});
files.Add(new File {Url = "tmp/cba.jpg", Id = "24"});
Now you are able to get desired json output with linq query:
var json = JsonConvert.SerializeObject(files.Select((f, i) => new {f, i})
.ToDictionary(key => $"file-{key.i}", value => value.f));
In my example result would be:
{
"file-0":{
"Url":"tmp/abc.jpg",
"Id":"42"
},
"file-1":{
"Url":"tmp/cba.jpg",
"Id":"24"
}
}