0

I'm trying to figure out how to iterate through a JSON object in an ASP.NET MVC controller. Every example I've come accross looks like the following where the posted JSON is assumed to contain a single object. However, let's say in my example below I want my controller to handle a collection of people rather than a single person. My inputModel therefore would contain a bunch of Names and Ages. For example, {"Name": "Bob", "Age": "30"},{"Name": "Paul", "Age": "19"}. How would you write your controller code to iterate through the people in the inputModel saving each one to that database?

Controller Code

[HttpPost]
public ActionResult Save(PersonInputModel inputModel) {
try{        
Person person = new Person();
person.Name = inputModel.Name;
person.Age = inputModel.Age;
Add(person);
Save(person);
}
catch {
//handle the error
}
}

1 Answer 1

2

Well assuming you are sending an array (notice the [] brackets around the JSON string because what you have shown in your question is not valid JSON):

[{"Name": "Bob", "Age": "30"},{"Name": "Paul", "Age": "19"}]

you could take an array:

[HttpPost]
public ActionResult Save(PersonInputModel[] persons) 
{
    foreach (var person in persons)
    {
        var name = person.Name;
        var age = person.Age;
        ...
    }
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

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.