I am making an ASP.NET/MVC app for some survey questions. I made a viewmodel that contains the questionid, the questiontext and the answertext. In the controller I create a list of these viewmodel and fill in the questionid and questiontext. I send the list as a model to the view. All the questions are shown to the user. After the users fills in the answers to the questions I want the list to be sent back to the controller. But the list is allways null.
This is the code in my controller:
public class EnqueteController : Controller
{
private BootCampEval.Models.DB_A2A0BC_bcenqEntities db = new Models.DB_A2A0BC_bcenqEntities();
// GET: Enquete
[Authorize]
public ActionResult CreateEnquete(int enqid = 1)
{
List<VMQuestion> questions = new List<VMQuestion>();
foreach (var q in db.GetQuestionsForEnquete(enqid))
{
var viewmodel = new VMQuestion();
viewmodel.EnqueteTitle = q.EnqTitle;
viewmodel.EnqueteDate = q.EnqDate;
viewmodel.QuestionID = q.QuestionID;
viewmodel.Question = q.Question;
viewmodel.Answer = "";
questions.Add(viewmodel);
}
return View(questions);
}
[Authorize]
[HttpPost]
public ActionResult HandleEnquete(List<VMQuestion> answers)
{
foreach (var a in answers)
{
var answer = new Answers();
answer.QuestionID = a.QuestionID;
answer.UserID = User.Identity.GetUserId();
answer.Answer = a.Answer;
db.Answers.Add(answer);
}
return View();
}
public ActionResult Index()
{
return View();
}
}
And this is my view:
@model IEnumerable<BootCampEval.ViewModels.VMQuestion>
@{
ViewBag.Title = "CreateEnquete";
int qnr = 1;
}
<h2>Enquete</h2>
@using (Html.BeginForm("HandleEnquete", "Enquete", FormMethod.Post))
{
<table>
@foreach (var q in Model)
{
<tr>
<td>
<h3>@qnr. @Html.DisplayFor(modelItem => q.Question)</h3>
</td>
</tr>
<tr>
<td>
@Html.TextAreaFor(itemModel => q.Answer, new { @class = "form-control", style = "min-width: 100%", @id = "Q" + @qnr })
</td>
</tr>
{ qnr++; }
}
</table>
<h2 style="text-align:center">Dank voor het invullen en je inzet!</h2>
<input type="submit" value="Insturen" class="btn btn-block" />
}