我在数据库表中有一个服务列表,我可以使用
在View中轻松显示@Modeltype IEnumerable(Of ServicesTestViewModel)
@For Each item In Model
@item.ServiceName
@<br/>
@item.ServiceDescription
@<br/>
@<br />
Next
我的ViewModel如下
Public Class ServicesTestViewModel
Public Property ServiceName As String
Public Property ServiceDescription As String
Public Property AdditionalQuestions As IEnumerable(Of ServiceAdditionalQuestions)
End Class
服务表与另一个名为AdditionalQuestions的表有关系,这是一个与id相关的服务问题列表。所以对于服务中的每一行都有一个附加问题列表,我想将它全部显示为列表。这是我的Linq与连接转换toList()
Function Index() As ActionResult
Using db As New EzipizyMarch2014Entities
Dim query = (From service In db.BusinessServices
Join additional In db.ServiceAdditionalQuestions On service.ID Equals additional.ServiceID
Select New ServicesTestViewModel With { _
.ServiceName = service.ServiceName, _
.ServiceDescription = service.ServiceDescription, _
.AdditionalQuestions = additional}).ToList
Return View(query)
End Using
End Function
我试图生成一个列表并填充每个服务的AdditionalQuestions
谢谢
修正了视图
@Modeltype IEnumerable(Of ServicesTestViewModel)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@For Each item In Model
@item.ServiceName
@<br/>
@item.ServiceDescription
@<br/>
@<br />
@<br />
@<br />
For Each question In item.MyQuestion
@question
@<br/>
Next
Next
</body>
</html>
修复了ViewModel,我使用了一个列表(字符串)而不是可以发生的
Public Class ServicesTestViewModel
Public Property ServiceName As String
Public Property ServiceDescription As String
Public Property MyQuestion As List(Of String)
End Class
修正了Linq查询
Function Index() As ActionResult
Using db As New EzipizyMarch2014Entities
Dim query = (From service In db.BusinessServices
Select New ServicesTestViewModel With { _
.ServiceName = service.ServiceName, _
.ServiceDescription = service.ServiceDescription, _
.MyQuestion = service.ServiceAdditionalQuestions.Select(Function(x) x.Question).ToList}).ToList
Return View(Query)
End Using
End Function
答案 0 :(得分:0)
我遇到了同样的问题,最后我决定创建一个列表并将List传递给我的视图而不是IEnumerable。
这是适用于我的代码示例。
[HttpGet]
public ActionResult List()
{
IOrderedEnumerable<MyDomainClass> MyDomainClassCol = MyServiceObject.GetList();
List<myViewModelClass> viewModelList = new List<myViewModelClass>();
foreach (var entity in MyDomainClassCol )
{
var myViewModelObject= new ViewModelClass();
entity.Map(myViewModelObject);
viewModelList.Add(myViewModelObject);
}
return View("List", myViewModelObject);
}
同样在我看来我得到了List,如下所示:
@model List<YourProjectName.YourViewModelClassName>
...
并且为了能够访问列表数据,请在<tbody> /tbody>
@foreach (var item in @Model) {
<tr>
<td>@item.YourViewModelMember1 </td>
<td>@item.YourViewModelMember2 </td>
<td>@item.YourViewModelMember3 </td>
</tr>
}