Well! I'm using ASP.MVC5. What I'm trying to do is to loop an array that contains objects and each object contains array properties:
I have this class:
public class MylistModels
{
public string Subtitle { get; set; }
public string[] Question { get; set; }
}
The logic is:
I have a POST form in HTML (I can add more fields if I want):
<input type="text" placeholder="Subtitle here" name="lists[0].Subtitle" />
<input type="text" placeholder="Subtitle here" name="lists[0].Question" />
<input type="text" placeholder="Subtitle here" name="lists[0].Question" />
<input type="text" placeholder="Subtitle here" name="lists[1].Subtitle" />
<input type="text" placeholder="Subtitle here" name="lists[1].Question" />
<input type="text" placeholder="Subtitle here" name="lists[1].Question" />
<input type="text" placeholder="Subtitle here" name="lists[2].Subtitle" />
<input type="text" placeholder="Subtitle here" name="lists[2].Question" />
<input type="text" placeholder="Subtitle here" name="lists[2].Question" />
When I click in save I send it to an action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(List<MylistModels> lists)
{
if (ModelState.IsValid)
{
//how to loop the arrays that contains a subtitle with questions array?
return RedirectToAction("Index");
}
return View();
}
When I receive it in the action, it looks like this:
I receive an array of objects and each one has your subtitle related to your questions
Obs.: the "subtitle" is always one in each object and "questions" I can have one or more.
PROBLEM:
How can I loop inside each object array and loop again in each question of this object?
I'm trying to do like this but it's not working:
SubtitleChecklist subtitleCheckList = new SubtitleChecklist();
QuestionChecklist questionChecklist = new QuestionChecklist();
foreach (var list in lists)
{
subtitleCheckList.IdChecklist = idChecklist;
subtitleCheckList.Subtitle = list.Subtitle;
db.subtitleCheckList.Add(subtitleCheckList);
db.SaveChanges();
int idSubtitleChecklist = subtitleCheckList.Id;
for (int i = 0; i < list.Question.Length; i++)
{
questionChecklist.Question = list.Question[i];
questionChecklist.IdSubtitle = idSubtitleChecklist;
db.QuestionChecklist.Add(questionChecklist);
db.SaveChanges();
}
}