Search code examples
razorasp.net-mvc-5

Difference Between Razor View taking a IEnumerable<Model> vs Model?


I have seen some people write @model IEnumerable<WebApplication1.Models.Weight> at the top of their view and some write @model WebApplication1.Models.Weight

I wanted to know the difference between both.Like when to use what?


Solution

  • A razor view which takes an IEnumerable<Entity> as a Model means that a collection of objects (e.g. view models, or entities) is passed as the Model to the page by the controller. e.g.

    @model IEnumerable<MyNamespace.Entity>
    

    would match a Controller action such as

    [HttpGet]
    public ActionResult SearchByName(string startsWith)
    {
        var entities = Db.Entities
           .Where(e => e.StartsWith(startsWith))
           .ToList();
        return View(entities);
    }
    

    So that the view will have access to multiple Entity objects (e.g. the page in question might be an Index or Search result page, where the entries could be listed in tabular fashion with a foreach)

    In contrast, a razor view which takes a single object as a Model is just showing the one object, e.g.

    @model MyNamespace.Entity
    

    Would 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 that the view has a single Entity model subject, e.g. the page might be showing the details of one Entity object, or allowing update, or insertion of just one Entity.

    The corresponding Model instance object available to the page will be the according type of the @model.

    One other point to note is that IEnumerable also expresses immutability, i.e. the View should read the collection, but may not e.g. Add or Delete entities from it (i.e. it is good practice to leave the scaffolded IEnumerable and not change this to e.g. IList or ICollection).