Reputation: 2871
I have a 'Survey' page which is declared as follows:
@using (Html.BeginForm("Survey", "Home", new { questionList = Model.Questions }, FormMethod.Post))
{
<div class="survey">
<ol class="questions">
@foreach (Question q in Model.Questions)
{
<li class="question" id="@q.QuestionName">
@q.QuestionText<br />
@foreach (Answer a in q.Answers)
{
<input class="answer" id="@a.DisplayName" type="checkbox" /><label for="@a.DisplayName">@a.AnswerText</label>
if (a.Expandable)
{
<input type="text" id="@a.DisplayNameFreeEntry" maxlength="250" /> <span>(250 characters max)</span>
}
<br />
}
</li>
}
</ol>
</div>
<div class="buttons">
<input type="submit" value="Finish" />
</div>
}
When I'm stepping through my code, it hits the method I've set up to process their survey:
[HttpPost]
public ActionResult Survey( List<Question> questionList, FormCollection postData)
{
//Process Survey
}
However, when I step through I am finding that the variable questionList
is null and the variable postData
does not contain any data from the Form. Trying to access checkboxes via Request[a.Displayname
also does not work.
Everything I've read indicates that this is the correct way to persist values from the Model to the submission method, and that I should be able to access the FormCollection this way.
What am I doing wrong?
Upvotes: 0
Views: 100
Reputation: 5691
The fact that the postData
is empty is weird, since every input element with id inside a form tag should be passed with the POST request.
But the questionList
won't be received that way, since its a list of complex class (not just a string or int), and the default ModelBinder
(the thing that turns the HTTP Request Variables into parameters passed to the action method) don't support lists of complex classes.
If you want to be able to receive List you will have to implement your own binding mechanism with CustomModelBinder
.
This article can help you implement it.
Upvotes: 1
Reputation: 6911
One problem is your checkbox and your textbox are not properly bound to your model.
You should be using @Html.CheckBoxFor
and @Html.TextBoxFor
Upvotes: 0
Reputation: 46750
You have to save questionList as a hidden field on the page. Non-primitive types do not get persisted simply by passing them in.
One way you can do that is
@Html.HiddenFor(m => m.Foo)
Or you could do it directly in HTML like this
<input type="hidden" name="Var" value="foo">
where m is your model.
Upvotes: 1