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

2

10

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!

Disunite answered 28/6, 2013 at 15:13 Comment(1)
Yes, foreach over List<ContractPlain> and display each Contract.Indistinctive
I
13

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>
Indistinctive answered 28/6, 2013 at 15:28 Comment(0)
W
5

If your action returns a List of contracts you can do the following in the view:

@model IEnumerable<ContractPlain>

@foreach(ContractPlain contract in Model) 
{
    <ul>
        <li>@contract.ContractGuid</li>
        <li>@contract.SenderId</li>
        <li>@contract.ContractStatus</li>
        <li>@contract.CreditEnd</li>
    </ul>
}
Watertight answered 28/6, 2013 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.