我制作了一个CRUD MVC应用程序,它有一些名为Parts
的东西,彼此之间存在某种关系。
PartMain - o:m Section, o:m Report
PartSection - m:o Main, o:m Property
PartProperty - m:o Section, Contains MainID for sorting purposes, SortByMainID
PartReport - m:o Main
所有型号都在工作,那一切都很好。现在,我希望生成一个视图,该视图将显示与所选的PartMain
相关的所有数据。像这样:
PartMain: Name, Desc, etc... rest of data
PartSection1: data...
PartProperty1: data.. (all properties in relationship with that section)
PartSection2: data... (all sections in relationship with selected PartMain)
PartProperty1: data.. (all properties in relationship with that section)
PartReport: data.... (all reports with selected PartMain)
我知道我应该在foreach
中执行类似View
循环的操作,但我无法掌握逻辑,有人可以帮忙吗?
感谢。
PartMain
包含名称和描述属性,也包含在o:m PartSection
和o:m PartReport
中。 PartSection
包含Name和Desc属性,也在o:m PartProperty
中。 PartProperty
包含名称和说明。 PartReport
包含名称和版本。
所以我想做的就是伪代码。 我在控制器中尝试了这个,用viewbag传递了数据但没有回来
pMainID = selectedMainID;
PartMain partMain = db.PartMain.Find(pMainID);
ViewBag.Name = partMain.Name
ViewBag.Desc = partMain.Desc
var partSections = db.PartSection.Where(s => s.pMainID = pMainID);
foreach (var partSec in partSections)
{
ViewBag.PartSecName = partSec.Name
ViewBag.PartSecDesc = partSec.Desc
var partProperties = db.PartProperties.Where(p => p.pSecID = partSec.ID);
foreach(var partProp in partProperties)
{
ViewBag.PartPropName = partProp.Name
ViewBag.PartPropDesc = partProp.Desc
}
}
现在应该输出像我上面提到的那样。当然这段代码不起作用,但这应该是一般的想法。这就是我寻求帮助的原因。谢谢。
答案 0 :(得分:1)
控制器:
var pMainID = selectedMainID;
PartMain partMain = db.PartMain.Find(pMainID);
ViewBag.Part = partMain;
ViewBag.Sections = db.PartSection
.Where(s => s.pMainID = pMainID)
.Select(s => new
{
Section = s,
Proeprties = db.PartProperties.Where(p => p.pSecID = partSec.ID)
});
查看:
<h1>@ViewBag.Part.Name</h1>
<p>@ViewBag.Part.Desc</p>
@foreach(var section in ViewBag.Sections)
{
<h2>@section.Section.Name</h2>
<p>@section.Section.Desc</p>
<dl>
@foreach(var property in section.Properties)
{
<dt>@property.Name</dt>
<dd>@property.Desc</dd>
}
</dl>
}