2012-08-10 69 views
0

我做了一个CRUD MVC应用程序,它有一些叫做Parts的应用程序,这些应用程序彼此处于某种关系。MVC3 Razor从模型中获取所有数据

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 PartReportPartSection包含名称和描述属性,也位于o:m PartPropertyPartProperty包含名称和说明。 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

我感动一切以查看使用'@ {}'内嵌代码和它的工作。 – rexdefuror 2012-08-10 07:58:19

+0

您的代码无法正常工作,因为每次您为ViewBag.XXX分配值时,都会丢弃旧值。 – deerchao 2012-08-10 10:12:29

+0

是的,我想通了,这就是为什么我把它作为内联。 – rexdefuror 2012-08-10 17:30:57

回答

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> 
} 
+0

我的第二个'代码'部分只是一个显示它应该看起来如何。我真的无法得到它的工作:(我会提供更多的代码,使其更清晰。 – rexdefuror 2012-08-10 07:01:22

+0

这是正确的答案,所以谢谢:) – rexdefuror 2012-08-10 17:36:11