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

戏子无情 提交于 2019-11-28 00:15:11

问题


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


来源:https://stackoverflow.com/questions/17368034/how-to-display-a-collection-in-view-of-asp-net-mvc-4-razor-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!