0

I'm trying to make a dynamic form for tests. My problem is when i submit that from, in post method in controller List gq is null, but im expecting to be filled with data that was filled in form. I can guess that it have to do something with @Html.EditorForModel() and data binding, but i dont fully understand how it works. Any idea? Thank you

Model:

public class GeneratedQuestions
{
    public int GeneratedQuestionsId { get; set; }

    public string QuestionText { get; set; }
    public List<StudentAnswer> QuestionAnswers { get; set; }

    public int StudentTestsId { get; set; } 
    public virtual StudentTest StudentTests { get; set; }
}

View:

@model IEnumerable<Project.Models.GeneratedQuestions>

@{
    ViewBag.Title = "StartTest";
}

@using (Html.BeginForm())
{
   @Html.EditorForModel()

    foreach (var question in Model)
    {
        <br />
        <h1>@question.QuestionText</h1>

        foreach (var answer in question.QuestionAnswers)
        {
            @Html.CheckBoxFor(x => answer.WasChecked)
            @Html.DisplayFor(x => answer.AnswerText)
            @Html.HiddenFor(x => answer.GeneratedQuestionsId)
            <br />
        }
    }
    <input type="submit" value="Submit" />
}

Controller:

public ActionResult StartTest(int id)
{
    List<GeneratedQuestions> generatedQuestions = db.StudentTests.Find(id).GeneratedQuetions.ToList();
    return View(generatedQuestions);
}


[HttpPost]
public ActionResult StartTest(List<GeneratedQuestions> gq)
{
    //stuff
    return RedirectToAction("Index");
}
ekad
  • 14,436
  • 26
  • 44
  • 46
VapoLolz
  • 3
  • 2
  • 4
    You need to use `for` instead of `foreach`. [Here](http://stackoverflow.com/questions/17037858/how-to-pass-ienumerable-list-to-controller-in-mvc-including-checkbox-state) is just one in many other similar questions regarding enumerable models and forms. – Andrei V Jun 19 '15 at 12:24

1 Answers1

0

As seen on here:

ASP.NET MVC 4 - for loop posts model collection properties but foreach does not

MVC helpers hate foreach loops. Go for a for loop and everything should work fine.

Write both loop and inspect them using web developer tools to see the difference in the 'id' and 'name' attribute.

Community
  • 1
  • 1
Quovadisqc
  • 81
  • 7