I need to access model data in a view 2 or 3 or n at a time RRS feed

  • Question

  • I am passing a simple model to my view from the controller.  No matter how I try,

    it seems that the only way to access the "entities"/rows in the model is via

    a foreach and iteratingover them sequentially.  I really need to get "entities" by their index value, by turning

    the model data from an IEnumerable into an array and getting entity[ n ].

    Is this possible or do I not understand the relationship between the View and

    the model data.

    Here's my call to the View:

    return View("ClientView", db.Clients.ToList());

    My model is a simple list of typical client properties with no navigation: FirstName, LastName, Address, etc.

    I'm trying to get client 1 in a left side div, and client 2 in a right side div,

    then a new row and start over.

    Thanks much in advance


    Tuesday, November 12, 2013 11:49 PM

All replies

  • I assume you're talking about asp MVC? If so the 'model' in the page is whatever you want it to be. You are not forced to make it enumerable. It can be anything you want.


    Tuesday, November 19, 2013 8:07 AM
  • Paul:

    Thanks. I got the answer I was seeking from Brendan Hill on Stackoverflow. For some reason I can't paste a link here, so here's his actual answer:

    Suppose your view is strongly typed to List:

    @Model List<MySoftware.Models.Client>

    Then you can access the clients by index:


    This is possible because the IList interface allows you to retrieve items by index, just like an array. A List is generally the preferred method as arrays are... well... a bit old fashioned.

    However, a better design might be to simply work this into your UI code instead, since this is really a UI display issue. Something like:

    @Model IEnumerable<MySoftware.Models.Client>
    var i = 0;
    foreach (var client in Model)
        <div> [client details] </div>
        if (i % 2 == 1)


    Tuesday, November 19, 2013 10:21 PM