我對 IList 的理解是它同時實作了 IEnumerable 和 ICollection。而List是IList介面的具體實作。
所以我在視圖命名空間中多次使用 IEnumerable 來迭代模型物件。但是當在命名空間中使用 IList 或 List 時,我得到一個
“/”應用程式中的服務器錯誤
所以,
- 為什么會這樣?和
- 如果我想使用 List 或 IList 應該怎么做?
控制器中的動作:
private DummyProjectContext db = new DummyProjectContext();
// GET: BankAccounts
public ActionResult Index()
{
List<BankAccount> ba = db.BankAccounts.ToList();
return View(ba);
}
索引.cshtml:
@model IList<DummyProject.Models.BankAccount>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Amount)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
好吧,我知道 IEnumerable 對于這個例子就足夠了,應該使用它。我想知道為什么使用 IList 或 List ,我收到此錯誤?
uj5u.com熱心網友回復:
您在問題中的代碼包含兩個錯誤并且無法編譯:
@Html.DisplayNameFor(model => model.Name)
...
@Html.DisplayNameFor(model => model.Amount)
...
您必須修復這些錯誤。
更新:
僅用于測驗,嘗試將上面的兩行替換為:
@Html.DisplayNameFor(model => Model.FirstOrDefault().Name)
和
@Html.DisplayNameFor(model => Model.FirstOrDefault().Amount)
使用 @model IList<DummyProject.Models.BankAccount> 并讓我知道是否會有任何變化。
uj5u.com熱心網友回復:
我創建了 Asp.net 專案并添加了一個虛擬串列,但我沒有收到該錯誤,也許您的串列物件為空。
控制器:
var s=new List<string>();
s.add("test");
return view(s);
view:
@model IList<string>
<ul>
@foreach(var item in Model)
{
<li>item</li>
}
</ul>
更多故障排除:請在運行專案時復制錯誤的所有堆疊跟蹤以查看完整錯誤。它可能是由于其他原因發生的。
uj5u.com熱心網友回復:
對于您的第一個問題:這是您專案中 URL 的路由映射
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
現在,當您的 Web 應用程式無法找到您的專案路徑時,會發生此錯誤我建議您學習更多有關 asp -MVC 中的路由的資訊,請查看此鏈接: Microsoft 檔案
對于你的第二個問題: System.Collections.Generic
這個命名空間用于集合泛型,現在你需要學習更多關于泛型和它們的差異,在它們之后你可以選擇其中一個可以幫助你查看這個鏈接:
泛型 | 微軟檔案
C# 中的 IEnumerable 與 IList
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/375270.html
標籤:C# 网站 asp.net-mvc
上一篇:我想從表中獲取行ID
下一篇:單擊側邊選單項時如何避免重繪頁面
