我想使数据库中的数据来自2个表中的数据。我查了一些东西,我试图使用ViewModel,但我无法让它工作。然后我考虑使用视图和局部视图来显示2个表中的数据。什么是使用ViewModel或使用视图和局部视图的最佳方式?MVC:在1视图中显示来自2个表的数据的最佳方式
此外,如果有人知道我在做什么我的ViewModel错误,并想帮助,这将是可怕的。
我的2种型号:
public partial class prospect
{
public prospect()
{
this.result = new HashSet<result>();
}
public int id { get; set; }
public int testid { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string email { get; set; }
public string cellnumber { get; set; }
public System.DateTime timestampstart { get; set; }
public Nullable<System.DateTime> timestampend { get; set; }
public Nullable<int> totalresult { get; set; }
public string birthdate { get; set; }
public string school { get; set; }
public Nullable<int> grade { get; set; }
public string address { get; set; }
public string cityandcode { get; set; }
public virtual ICollection<result> result { get; set; }
public virtual resultpersection resultpersection { get; set; }
}
public partial class resultpersection
{
public int id { get; set; }
public int prospectid { get; set; }
public int sectionid { get; set; }
public Nullable<int> result { get; set; }
public virtual prospect prospect { get; set; }
public virtual section section { get; set; }
}
我想要显示的东西: prospect.name,prospect.surname,prospect.totalresult和所有每这一前景的部分结果(这来自resultpersection表)
我的视图模型:
namespace testAptitude.Models
{
public class ResultsPerProspect
{
public List<prospect> prospect { get; set; }
public List<resultpersection> resultPerSection { get; set; }
}
}
我控制器
public ActionResult Index()
{
ResultsPerProspect vm = new ResultsPerProspect();
vm.prospect = (from p in db.prospect select p).ToList();
vm.resultPerSection = (from rps in db.resultpersection select rps).ToList(); ;
List<ResultsPerProspect> viewModelList = new List<ResultsPerProspect>();
viewModelList.Add(vm);
return View(viewModelList.AsEnumerable());
}
我看来
@model IEnumerable<testAptitude.Models.ResultsPerProspect>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<thead>
<tr>
<th class="col-sm-3">
@Html.DisplayNameFor(model => model.prospect)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.prospect)
</td>
</tr>
}
</tbody>
</table>
我不能这样做item.prospect.name,因为它说的是不包含定义名称
和现在dispalys是这样的:
前景
System.Collections.Generic.HashSet`1 [testAptitude.Models.result]
提前致谢!
你能解释一下吗?我已经通过foreach迭代了列表?你能给一个代码示例吗? – kicked11
请检查我的更新 –
oke谢谢,这就是我所需要的! – kicked11