2012-08-10 46 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