c# - How to send back data from multiple auto-generated fields from view to controller -
i'm building application allows users go trough series of questions , select response 4 pre-determined options. problem i'm facing how send data controller. have object game
holds property questions
while each question holds code
, question
, answer
, string
type.
i've created page displays every question , answer in dropdownlist (once figure out how place radiobuttons, i'll use that), i'm stumped how should send results controller: every select
element in generated html
code has same id
, how can distinguish question-answer relationship other?
are there alternative approaches better? i've tried working partialview
each question, if possible i'd stick 1 page list of questions.
the code i'm using create current view 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 send answers controller in way tells me answer meant question's code.
you can't use foreach
bind lists because name fields won't indexed (so model binder doesn't know them). need use for
loop. try this:
for (int = 0; < 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> }