How to display a collection in View of ASP.NET MVC 4 Razor project?

user2402179 picture user2402179 · Jun 28, 2013 · Viewed 39.1k times · Source

I have the following Model:

public class ContractPlain
{
    public int Id { get; set; }
    public Guid ContractGuid { get; set; }
    public int SenderId { get; set; }
    public int RecvId { get; set; }
    public int ContractType { get; set; }
    public string ContractStatus { get; set; }
    public DateTime CreatedTime { get; set; }
    public DateTime CreditEnd { get; set; }
}

public class Contrtacts
{
    List<ContractPlain> listOutput;

    public void Build(List<ContractPlain> listInput)
    {
        listOutput = new List<ContractPlain>();
    }

    public List<ContractPlain> GetContracts()
    {
        return listOutput;
    }

    internal void Build(List<contract> currentContracts)
    {
        throw new NotImplementedException();
    }
}

As you can see, I defined a whole collection.

Why?

I need to render the data in table for user, because there are several rows which belongs to the exact/unique user (e.g. 20-30 shop items are referred to the single client).

So, I'm getting data from the DB using ADO.NET Entity. The binding question to the model instance in Controller is done and I don't have issues with that, I do with the rendering question only.

I think, it could be used with the @for stuff, but didn't know, how it would be better using especially my custom model.

So, how can I render the data in View using my model?

Thanks!

Answer

Sam Leach picture Sam Leach · Jun 28, 2013

See the view below. You simply foreach over your collection and display the Contracts.

Controller:

public class ContactsController : Controller
{
   public ActionResult Index()
   {
      var model = // your model

      return View(model);
   }
}

View:

<table class="grid">
<tr>
    <th>Foo</th>
</tr> 

<% foreach (var item in Model) { %>

<tr>
    <td class="left"><%: item.Foo %></td>
</tr>

<% } %>

</table>

Razor:

@model IEnumerable<ContractPlain>

<table class="grid">
<tr>
    <th>Foo</th>
</tr> 

@foreach (var item in Model) {

<tr>
    <td class="left"><@item.Foo></td>
</tr>

@}

</table>