我有一份包含项目列表的公司列表。我想显示所有公司和所有项目,如:
Company1
Project1
Project2
Company2
Project3
Project4
如何使用asp.net MVC5轻松完成此任务?
编辑: 我需要一个具体的视图示例,以便我能够理解如何创建控制器和模型。这是我的控制器和模型。
Public Class CompanyModel
Private _title As String
Private _projects As New List(Of Project)
Public Property title As String
Get
Return _title
End Get
Set(value As String)
_title = value
End Set
End Property
Public Property projects As List(Of Project)
Get
Return _projects
End Get
Set(value As List(Of Project))
_projects = value
End Set
End Property
End Class
和控制器功能:
Function Index() As ActionResult
Dim Companies As New List(Of CompanyModel)
Using db As New ProjectDBDataContext(ConnectionStrings("redacted").ConnectionString)
Dim companyList = (From c In db.Companies Select c)
For Each c In companyList
Dim projects = (From p In db.Projects Where p.companyID = c.id Select p).ToList
Companies.Add(New CompanyModel With {.title = c.title, .projects = projects})
Next
End Using
Return View(Companies)
End Function
然后我只使用了Chris的示例代码来进行视图。
答案 0 :(得分:1)
您应该能够在视图中使用嵌套的For Each使用Razor来实现此目的。
编辑:可能的解决方案:
查看:
@foreach (var company in Model) {
@company.Name
@Html.Partial("_Projects", company.Projects)
}
_Projects partial view:
@foreach (var project in Model) {
@project.Name
}