I’m building a questionnaire mvc webapp, and i cant figure out how to pass an unknown number of arguments to the controller from the form.
My form is something like:
<% using (Html.BeginForm()) { %> <div id='Content'> <% foreach (var group in ViewData.Model.QuestionGroups) { %> <div class='Group'> <%=group.Description %> <% foreach (var question in group.Questions) {%> <div class='Question'> <div class='QuestionTitle'> <%=question.Title %> </div> <%=Html.Hidden('Id', question.ID) %> <div class='QuestionText'> <%switch (question.TypeAsEnum) { case QuestionTypeEnum.Text:%> <%=Html.TextBox('somename') %> <% break; case QuestionTypeEnum.Number:%> <%=Html.TextBox('somename') %> <% break; case QuestionTypeEnum.PhoneNumber:%> <%=Html.TextBox('somename')%> <% break; case QuestionTypeEnum.Email:%> <%=Html.TextBox('somename')%> <% break; case QuestionTypeEnum.Date:%> <%=Html.TextBox('somename')%> <% break; case QuestionTypeEnum.YesNo:%> <%=Html.RadioButton('somename', true)%> <%=Html.RadioButton('somename', false)%> <% break; case QuestionTypeEnum.Alternative:%> <%=Html.DropDownList('somename', question.Answers)%> <% break; }%> </div> </div> <% } %> </div> <% } %> </div> <div id='submittButton'> <%=Html.SubmitButton()%></div> <% } %>
Now what i need in my controller is List< ResponseAnswer >, where ResponseAnswer has the properties:
string questionID, string AnswerText, bool AnswerBool, number AnswerNumber, …
So how can i pass an unknown number of items containing questionID, AnswerType and Answer to the controller. In webforms i solved this by rendering the form with repeaters instead of foreach, and then iterating through the question repeater checking the control id, each repeater item containing a hidden questionid element and a input with id=AnswerType. But this will seriously break Separation of concern in mvc?
So is there any way of getting my controller to accept List< ResultAnswer > and somehow build this list without breaking soc, and if not, how do i pass the entire formresult back to the controller so i can do the iteration of the form data there instead of in the view.
Garry’s answer will work (and hence, up voted). However, you can model bind directly to a list, and I think it’s a bit more elegant. There are instructions in this blog post.