在 MVC 视图中使用 Razor 遍历模型 属性

Loop through Model property with Razor in MVC View

我有这个模型有很多属性

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

我需要在视图中创建一个table来列出任务的所有属性。

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

有什么想法吗?

请使用这个

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

        <td>
          @task.Title 
        </td>

    </tr>
}

其他属性依此类推。然后在你的控制器中你 return 一个任务列表,比如

`return View(your taskList);`

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

像这样

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

这对你有用吗?

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

史蒂夫·库珀示例的扩展:


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