在MVC视图中使用Razor循环模型属性

时间:2016-05-05 19:14:10

标签: c# asp.net-mvc razor model viewdata

我有这个有很多属性的模型

public class Task {
    public string Key { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    ....
}

我需要在View中创建一个表来列出Task的所有属性。

已经问过同样的问题,但我不想使用ViewData:Looping through view Model properties in a View

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

这对你有用吗?

@foreach(var task in Model) {
    <tr>
    @foreach(var property in typeof(Task).GetProperties()) {
        <th>@(property.GetValue(task, null))</th>
    }
    </tr>
}

答案 1 :(得分:1)

您可能需要使用反射来获取属性。

像这样的东西

@model List<Task>
@if(Model.Any())
{
   var propArr = Model.Events[0].GetType().GetProperties();
   foreach (var ev in Model)
   {
      var p = ev.GetType().GetProperties();
      foreach (var propertyInfo in propArr)
      {
         <h4>@propertyInfo.Name</h4>     
         var val = propertyInfo.GetValue(ev, null);
         if (val != null)
         {
             <p>@val</p>
         }
      }        
    }
}

答案 2 :(得分:0)

请使用此

@foreach (var task in Model)
{    
    <tr>

        <td>
          @task.Title 
        </td>

    </tr>
}

等等其他属性。然后在你的控制器中你返回一个像

这样的任务列表
`return View(your taskList);`

答案 3 :(得分:0)

以史蒂夫·库珀(Steve Coopers)为例进行了扩展:


    <table class="table table-bordered table-responsive table-hover">
                        @foreach (var item in Model.a)
                        {
                            <tr>
                               @foreach (var prop in typeof(a).GetProperties())
                               {
                                   <th>@(prop.Name)</th>
                               }
                            </tr>
                            <tr>
                                @foreach (var prop in typeof(a).GetProperties())
                                {
                                    <td>@(prop.GetValue(item, null))</td>
                                }
                            </tr>
                        }
                    </table>