簡體   English   中英

使用Html.RenderPartial在父視圖和子視圖之間進行C#ASP.NET MVC錯誤共享模型

[英]C# ASP.NET MVC error sharing model between parent and child view using Html.RenderPartial

調用@Html.RenderPartial("_ChildPartialView")時,出現以下錯誤:

System.Collections.Generic.ICollection'沒有適用的名為'ElementAt'的方法,但似乎具有該名稱的擴展方法。 擴展方法不能動態調度。 考慮強制轉換動態參數或在不使用擴展方法語法的情況下調用擴展方法

_Testpaper.cshtml父視圖:

    for (i = 0; i < Model.Questions.Count;i++)
    {
        ViewBag.QuestionNumber = i;
        Html.RenderPartial("_QuestionDetail"); //Line causing error
    }

_QuestionDetail.cshtml子視圖:

@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) &nbsp @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>

我還想知道:當子視圖在RenderPartial調用中共享同一模型時,為什么必須在子視圖中指定@Model

您需要像這樣將模型傳遞給子局部視圖:

for (i = 0; i < Model.Questions.Count;i++)
{
    ViewBag.QuestionNumber = i;
    Html.RenderPartial("_QuestionDetail", Model.Questions[i]); //Line causing error
}

確保Model.Questions [i]的類型與子局部視圖“ @model StandardVBA.ViewModels.AssessmentModel ”中的模型聲明匹配,否則會出現運行時錯誤。

希望能幫助到你。

首先,您沒有將模型傳遞給子視圖,而是在子視圖中使用@model,因此通過將模型傳遞給子視圖來修復它,如下所示:

    for (i = 0; i < Model.Questions.Count;i++)
    {
        ViewBag.QuestionNumber = i;
        Html.RenderPartial("_QuestionDetail", Model); //Line causing error
    }

其次,您在詳細視圖中使用@ Html.CheckBoxFor(m => m.Questions .......),這是您的子視圖,因此您需要聲明@model ......以在您的意見。

希望這會成功!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM