Skip to main content
 首页 » 编程设计

c#之在 MVC View 中使用 Razor 循环遍历模型属性

2024年02月05日11www_RR

我有这个模型有很多属性

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

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

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

有什么想法吗?

请您参考如下方法:

这对你有用吗?

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