I have this this View for rendering form
@using ExpertApplication.ViewModels
@model IEnumerable<QuestionViewModel>
@{
ViewBag.Title = "GetQuestions";
}
@using(Html.BeginForm("ProcessAnswers", "Home", FormMethod.Post))
{
foreach(QuestionViewModel questionViewModel in Model)
{
Html.RenderPartial("QuestionPartialView", questionViewModel);
}
<input type="submit" value="Send data"/>
}
}
<h2>GetQuestions</h2>
And partial view
@using ExpertApplication.ViewModels
@model QuestionViewModel
<div id="question">
@Model.Text
<br />
<div id="answer">
@foreach(var answer in Model.AnswerViewModels)
{
@(Model.IsMultiSelected
? Html.CheckBoxFor(a => answer.Checked)
: Html.RadioButtonFor(a => answer.Checked, false))
@Html.LabelFor(a => answer.Text)
<br />
}
</div>
</div>
I want get data from From
[HttpPost]
public ActionResult ProcessAnswers(IEnumerable<QuestionViewModel> answerForQuesiton)
{
//answerForQuestion always is null
}
but parameter answerForQuesiton is null. How to fix this problem ?
MVC binds lists by using zero indexed names. Unfortunately, for this reason, while
foreachloops will create inputs that contain the correct values, they will not create input names that use the correct names. Therefore, you cannot bind lists usingforeachFor example:
Will create textboxes with names like “Foo[1].Bar[2].myValue” and correctly bind. However,
will create text boxes with the exact same values as the prior loop, but all of them will have “name=”bar.myVal” so none of them can bind.
So to fix your issue:
1) You could replace your foreach loops with for loops. Note: this requires using
IListorListinstead ofIEnumerable2) You could use EditorTemplates which automatically apply the correct names for you.