I'm building an application which allows users to go trough a series of questions and select their response from 4 pre-determined options. The problem I'm facing is how to send data back to the controller. I have an object Game
which holds a property Questions
while each question holds a Code
, Question
and Answer
, all string
type.
I've created a page which displays every question and the answer in a dropdownlist (once I figure out how to place it as radiobuttons, I'll use that), but I'm stumped as to how I should send the results back to the controller: every select
element in the generated HTML
code has the same id
, so how can I distinguish a question-answer relationship from any other?
Are there alternative approaches that would be better? I've tried working with a PartialView
for each question, but if possible I'd like to stick to one page with a list of questions.
The code I'm using to create my current view is this:
@using (Html.BeginForm("Save", "Game", FormMethod.Post)) {
foreach (var question in Model.Questions) {
<div class="question">
<h4>@vraag.Vraag</h4>
@Html.DropDownListFor(x => question.Code, new SelectList(question .Answers))
@Html.HiddenFor(x => question.Code)
</div>
}
<input type="submit" value="Save" />
}
I want to send all answers back to my controller in a way that clearly tells me which answer is meant for what question's code.
You can't use a foreach
to bind lists because their name fields won't be indexed (so model binder doesn't know what to do with them). You need to use a for
loop. Try this:
for (int i = 0; i < Model.Questions.Count; i++) {
<div class="question">
<h4>@vraag.Vraag</h4>
@Html.DropDownListFor(x => x.Questions[i].Code, new SelectList(Model.Questions[i].Answers))
@Html.HiddenFor(x => x.Questions[i].Code)
</div>
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.