Difference between Razor view using IEnumerable <Model> vs Model?
A razor view that takes IEnumerable<Entity>
as a model means that a collection of objects (such as a view model or entity) is passed as a model to the page by the controller. eg.
@model IEnumerable<MyNamespace.Entity>
will match the Controller action like
[HttpGet]
public ActionResult SearchByName(string startsWith)
{
var entities = Db.Entities
.Where(e => e.StartsWith(startsWith))
.ToList();
return View(entities);
}
For a view to have access to multiple objects Entity
(for example, the page in question can be a page, Index
or Search result
where records can be tabulated with foreach
)
In contrast, a razor view that takes one object as a model simply shows one object, for example.
@model MyNamespace.Entity
Will be used from a controller action such as
[HttpGet]
public ActionResult Details(int id)
{
var entity = Db.Entities.Find(id);
if (entity == null)
return HttpNotFound();
return View(entity);
}
means the view has one model object Entity
eg. the page can display information about one object, Entity
or only update or insert one is allowed Entity
.
The corresponding object type Model
available to the page will match the type @model
.
Another point to note is that it IEnumerable
also expresses immutability, i.e. the view must read the collection, but cannot, for example, Add
or Delete
entities from it (that is, it is good practice to leave left IEnumerable
and not change it, for example, IList
or ICollection
).
source to share