My understanding about IList is it implements both IEnumerable and ICollection.
and List is a concrete implementation of IList interface.
So I had used IEnumerable in the view namespaces many times to iterate over model objects.
But when using IList or List in the namespaces, I’m getting an
Server Error in ‘/’ Application
So,
- Why is this happening? and
- If I want to use List or IList what should be done?
Action in Controller :
private DummyProjectContext db = new DummyProjectContext();
// GET: BankAccounts
public ActionResult Index()
{
List<BankAccount> ba = db.BankAccounts.ToList();
return View(ba);
}
Index.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>
Well, I know there IEnumerable is sufficient for this example and that should be used. I want to know why using IList or List , I’m getting this error?
3
Answers
I Created Asp.net Project And Added a Dummy List But I Have not gotten that error Maybe Your list Object Is Null.
Controller:
For More trouble shooting:
Please copy all the stack trace of an error when You run project for seeing complete error. It maybe occurred for other reason.
Your code in the question contains two errors and doesn’t compiling:
You have to fix these errors.
UPDATE:
Just for test, try to replace two lines above by:
@Html.DisplayNameFor(model => Model.FirstOrDefault().Name)
and
@Html.DisplayNameFor(model => Model.FirstOrDefault().Amount)
Use
@model IList<DummyProject.Models.BankAccount>
and let me know if will be any changes.You’ll get an error here. Use Inumerable will resolve this error.