I need to pass json to the controller in MVC. My method returns a list of strings, which is then translated to json with array of strings. Because of some front end complexities I should return the result as array of basic objects e.g. instead of ["Item1", "Item2", "Item3"] etc. i need to pass [{item: "Item1"}, {item: "Item2"}, {item: "Item3"}].
I created something that works, but it would require a lot of repetition. I was wondering if there was already something built-in, or just a better logic to accomplish such tasks.
A new super basic class:
public class ObjectConverted
{
public string item { get; set; }
}
A converter class:
public class Converter
{
public List<ObjectConverted> convertToObjects(IEnumerable<string> listOfStrings)
{
List<ObjectConverted> listConverted = new List<ObjectConverted>();
foreach (string i in listOfStrings)
{
ObjectConverted oc = new ObjectConverted();
oc.item = i;
listConverted.Add(oc);
}
return listConverted;
}
}
and pass it to the controller like:
public ActionResult Competitors()
{
IEnumerable<string> strings = getItemStrings();
Converter c = new Converter();
List<ObjectConverted> objects = c.convertToObjects(strings);
return Json(objects, JsonRequestBehavior.AllowGet);
}