2011-10-21 19 views
2

型號/ Db的實體關係(基線佔位符文學內容):如何在索引和編輯視圖(強綁定)中傳遞和合並MVC3中的兩個模型?

public class TitlePercent 
{ 
    public int TitleName; 
    public decimal Percentage;  
} 

public class TitleMonthly 
{ 
    public string Month; 
    public int Val; 
} 

基數=> 1 TitlePercent到* TitleMonthly

畫報視圖(建議):

_____________________________ 
Name | % || Jan | Feb | 
_____________________________ 
Title1 2%  23 343 
Title2 3%  343 3434 
_____________________________ 

控制器(提出) :

// Need view and edit 
    public ViewResult ViewTitlePercentAndTitleMontly() 
    { 
     return View(db.<NotSureWhatWouldGoHere>.ToList()); 
    } 

    public ActionResult EditTitlePercentAndTitleMontly(int id) 
    { 
     return View(db.<NotSureWhatWouldGoHere>.Find(id)); 
    } 

剃刀Vi EW(建議僞): ...查看和編輯 @model MVC3.Models.TitlePercent @ MODEL2 MVC3.Models.TitleMonthly

1. For Index View to show the grid not sure how to mash this up (like the grid) 
    - Perhaps build this in the controller but not sure how to build and pass that to the view as 
    I have had not dealt with multiple models as relationships. 
2. For Edit View need to figure out how to bind to a model similar to: 
    @Html.EditorFor(model => model.TitleName) 
    @Html.EditorFor(model => model.Percentage) 

    foreach TitleMonthly in TitlePercentag 
    { 
     @* Iterate and bind somehow *@ 
     @Html.EditorFor(model2 => model2.Month) 
     @Html.EditorFor(model2 => model2.Val) 
    } 
    ??? 

對不起,缺乏細節和僞代碼,但我只是避風港」 t必須處理多個模型,特別是如果它們是相互關聯的/依賴關係,並且可以通過連接的類/表創建網格視圖....那麼如果要編輯一行(兩個類的組合),則如何將所有關係綁定到基於這兩個類模型的文本框中)?

再次,我會提交嘲笑這一個,但任何信息和例子將不勝感激。

+0

Mariah,這對我來說也是一個絆腳石。 –

回答

3

通常你會使用一種叫做ViewModel的東西,這是一個爲視圖設計的非常具體的模型。您可以使用數據模型中的信息填充該模型,然後將其傳遞給視圖。它不一定要有1:1的結構,這可以讓你獲得更多的信息或者更少的信息,這取決於你的需求。

對編輯器模型,你可以創建類似視圖模型:

public class TitleEditingViewModel { 
    public TitlePercent TitlePercent {get;set;} 
    public ICollection<TitleMonthly> MonthlyTitles {get;set;} 
} 

你會再填充該模型無論你在控制器希望再模型傳遞到視圖。

@Html.EditorFor(model => model.TitlePercent.TitleName) 
@Html.EditorFor(model => model.TitlePercent.Percentage) 

@foreach titleMonthly in Model.MonthlyTitles { 
    @Html.EditorFor(model => titleMonthly.Month) 
    @Html.EditorFor(model => titleMonthly.Val) 
} 
+0

嗨BuildStarted:我如何映射這個自定義視圖?我從我的視野中得到空值? – Mariah

相關問題