How to display a collection in View of ASP.NET MVC

2020-02-10 23:30发布

问题:

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!

回答1:

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>


回答2:

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>
}