While invoking @Html.RenderPartial("_ChildPartialView")
, I am getting the following error :
System.Collections.Generic.ICollection' has no applicable method named 'ElementAt' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax
_Testpaper.cshtml parent view:
for (i = 0; i < Model.Questions.Count;i++)
{
ViewBag.QuestionNumber = i;
Html.RenderPartial("_QuestionDetail"); //Line causing error
}
_QuestionDetail.cshtml child view:
@model StandardVBA.ViewModels.AssessmentModel
<tr style="padding:4px 0px; background-color:lightskyblue; font-weight:bold;font-family:Cambria;">
<td style="text-align:left;">
Q @(ViewBag.QuestionNumber + 1)   @Model.Questions.ElementAt(ViewBag.QuestionNumber).Question
</td>
<td style="text-align:center">
( @Model.Questions.ElementAt(ViewBag.QuestionNumber).Marks )
</td>
</tr>
<tr>
<td class="questions">
<ol type="A">
@for (int j = 0; j < Model.Questions.ElementAt(ViewBag.QuestionNumber).QuestionDetails.Count; j++)
{
<li>
<div style="display: inline-block; vertical-align: top;">
@Html.CheckBoxFor(m => m.Questions.ElementAt(ViewBag.QuestionNumber).QuestionDetails.ElementAt(j).IsSelected)
</div>
@Html.DisplayFor(m => m.Questions.ElementAt(ViewBag.QuestionNumber).QuestionDetails.ElementAt(j).Choice)
@Html.HiddenFor(m => m.Questions.ElementAt(ViewBag.QuestionNumber).QuestionDetails.ElementAt(j).IsCorrect)
</li>
}
</ol>
</td>
</tr>
I also want to know: why it is mandatory to specify the @Model
in the child-view when the child-view shares the same model in a RenderPartial
call?
You need to pass the model to the child partial view like this:
for (i = 0; i < Model.Questions.Count;i++)
{
ViewBag.QuestionNumber = i;
Html.RenderPartial("_QuestionDetail", Model.Questions[i]); //Line causing error
}
Ensure that the type of Model.Questions[i] matches with the model declaration in the child partial view "@model StandardVBA.ViewModels.AssessmentModel" otherwise you will get the runtime error.
Hope it helps.