[英]Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
[英]Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
我在asp.net mvc-4 Web應用程序中的視圖中有以下代碼: -
@model IList<TS.ViewModels.ACCOUNTLIST>
@for(int i2 = 0; i2 < (Model.Count() <= 0 ? 5 : Model.Count()); i2++) {
<div>
<span >@Html.DisplayFor(m => m[i2].ACCOUNTNAME) </span>@Html.EditorFor(m => m[i2].ACCOUNTNAME) </div>
<div>
<span >@Html.DisplayFor(m => m[i2].PASSWORD) </span>@Html.EditorFor(m => m[i2].PASSWORD) </div>
<div>
<span >@Html.DisplayFor(m => m[i2].NOTES) </span>@Html.EditorFor(m => m[i2].NOTES) </div>
}
現在我想要完成的是如果模型為空,則顯示一組五個空字段。 並且在案例中,模型包含顯示相關日期的數據..但是當前我渲染視圖並且傳遞的模型為空時,我將得到以下異常: -
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
但如果我使用Html.Display
和Html.Editor
如下,我的觀點將運作良好: -
@for(int i2 = 0; i2 < (Model.Count() <= 0 ? 5 : Model.Count()); i2++) {
<div>
<span class="f">@Html.Display("["+i2.ToString()+"].ACCOUNTNAME") </span>@Html.Editor("["+i2.ToString()+"].ACCOUNTNAME")
<span class="f">@Html.Display("["+i2.ToString()+"].PASSWORD") </span>@Html.Editor("["+i2.ToString()+"].PASSWORD") </div>
}
所以有人可以這樣做嗎? 為什么我不能在我的情況下使用Html.DisplayFor
和Html.EditorFor
?
問題是您正在嘗試從集合中檢索不存在的項目。 例如,嘗試從3的集合中訪問對象4。
為了解決你遇到的問題,我要從視圖中刪除條件,而是將其放在控制器中,這樣如果你希望將來顯示更多的空條目,你根本不需要修改視圖。
用以下內容替換語句視圖:
@for (var i2 = 0; i2 < Model.Count; i2++)
{
<div>
<span>@Html.DisplayFor(m => m[i2].ACCOUNTNAME)</span>@Html.EditorFor(m => m[i2].ACCOUNTNAME)
</div>
<div>
<span>@Html.DisplayFor(m => m[i2].PASSWORD) </span>@Html.EditorFor(m => m[i2].PASSWORD)
</div>
<div>
<span>@Html.DisplayFor(m => m[i2].NOTES) </span>@Html.EditorFor(m => m[i2].NOTES)
</div>
}
然后你的控制器里面有一些東西
// Replace this with your method of retrieving the accounts list
var accounts = new List<ACCOUNTLIST>();
const int maxEntries = 5;
while (accounts.Count < maxEntries)
{
accounts.Add(new ACCOUNTLIST());
}
return View(accounts);
這種情況有點奇怪:
i2 < (Model.Count() <= 0 ? 5 : Model.Count());
它所聲明的是,如果模型計數小於或等於零,則循環5次,否則循環“模型計數”次。
因此,當模型為空時,它將嘗試訪問Model
中不存在的前5個元素 - 因此出現錯誤。
當計數為零時,你需要決定你想要發生什么,並明確地代碼:
if (Model.Count() > 0)
{
@for(int i2 = 0; i2 < Model.Count(); i2++)
{
}
}
else
{
Do something else
}
看來你是綁定空模型數據集合。 我想如果你在Action結果中為你的模型集合設置一些默認值並渲染它會更好,而不是發送一個空List。 而且,您只需檢查默認值並相應地創建字段,而不是檢查您的模型是否為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.