通过与MVC视图剃刀Model属性环路

问题描述 投票:1回答:4

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

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

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

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

任何想法?

c# asp.net-mvc razor model viewdata
4个回答
2
投票

这是否为您工作?

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

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

0
投票

请使用此

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

        <td>
          @task.Title 
        </td>

    </tr>
}

等等其他属性。然后在你的控制器u返回像任务列表

`return View(your taskList);`

0
投票

扩展史蒂夫·库珀举例:


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

© www.soinside.com 2019 - 2024. All rights reserved.