I'm being told that putting a direct reference to IQueryable from an ASP.NET MVC view is a bad practice but I have not found any clear explanation for that. Some might have experienced a "disposed object" error when accessing an IQueryable or a DbContext in a view but it is not a problem I am concerning about.
Here is how I implement a simple controller and a view that contains a list of users
public ActionResult Index()
{
return View(db.Users);
}
In my view
@model IEnumerable<User>
<ul>
@foreach (var user in Model)
{
<li>@user.UserName</li>
}
</ul>
And I'm being told that I should return a "collection object" instead of passing IQueryable to the view.
public ActionResult Index()
{
return View(db.Users.ToList());
}
I'm a little bit curious about why I have to do that. I can say that the latter approach is worse than my first approach because the dataset is iterated twice in my application, first to construct the List
object by the ToList()
method, second by the foreach
loop in my view to render <li>
items.
So that means the latter approach must have a better point somewhere that I have not found out yet. Even in ASP.NET forum or Microsoft MSDN site, they also provides examples of the latter approach but did not give any reason on that, or am I missing something?
Can any one explain this simple basic stuff for me?
Many thanks.