2

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);
}

1 Answer 1

4

how about converting it into linq which returns anonymous class?

public ActionResult Competitors()
{
    return Json(getItemStrings().Select(x => new { Item = x }), JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, this line works exactly the same as mine 20+:) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.