Reputation: 1129
I would like to loop through a result in a view from a call to a LINQ to SQL function that returns a list of objects. However, I am not sure how to get the view to handle the L2S object (in order to use a foreach).
In the controller:
ViewData["list"] = db.Users.ToList();
Upvotes: 0
Views: 1870
Reputation: 69904
Controller:
public class MyClassController : Controller
{
private ProjectContext db = new ProjectContext();
//
// GET: /MyClass/
public ViewResult Index()
{
return View(db.MyClasses.ToList());
}
}
View:
@model IEnumerable<MvcApplication1.Models.MyClass>
@foreach (var item in Model) {
<div>
<!-- HTML here like @item.Title -->
</div>
}
This is the strongly typed view methodology. Using the dynamic approach it isn't much different. Just assigning your list to a property on the dynamic object and then instead of foreach(var item in Model)
it becomes foreach(var item in ViewBag.listProperty)
. Or with ViewData you assign ViewData.Add('list', db.MyClasses.ToList())
and the foreach becomes foreach(var item in ViewData['list'])
I prefer the strongly typed approach as it seems much much cleaner.
EDIT: good point brought up in comments (that I forgot since I almost exclusively use the strongly typed approach) is that you'll have to cast out. In this case it is stored as a List<MyClass>
though you can also implicitly pull it out as an IEnumerable<MyClass>
Upvotes: 1