我在 asp.net mvc-4 web 应用程序的 View 中有以下代码:-
@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>
}
现在我想要完成的是,如果模型为空,则显示五个空的字段集。万一模型包含显示相关日期的数据..但是目前当我呈现 View 并且传递的模型为空时我将得到以下异常:-
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
但如果我按如下方式使用 Html.Display 和 Html.Editor,我的 View 将运行良好:-
@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。
为了解决您遇到的问题,我将从 View 中删除条件并将其放入 Controller 中,这样如果您希望将来显示更多空条目,则根本不需要修改 View .
将语句的 View 替换为以下内容:
@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>
}
然后在你的 Controller 里面有一些东西
// 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);
