2013-09-26 27 views
0

我有2個模型。在mvc中合併2個相關模型

public partial class Question 
    { 
     public int QuestionId { get; set; }   
     public string QuestionText { get; set; } 
     public string Ans1 { get; set; } 
     public string Ans2 { get; set; } 
     public string Ans3 { get; set; } 
     public string Ans4 { get; set; } 
    } 
    public partial class UserAnswer 
    { 
     public int UserAnsId { get; set; } 
     public Nullable<int> QuestionId { get; set; } 
     public Nullable<int> UserId { get; set; } 
     public Nullable<int> AnsVal { get; set; }   
    } 

正如你可以看到QuestionId在兩個模型中。我如何在視圖中渲染它。有很多問題。問題Moldel在初始運行時有數據,但UserAnswer沒有。

如何組合這兩個模型,以便我可以將它用作IEnumerable中的視圖。 Ans1,Ans2,Ans3,Ans4在UserAnswer中有文本和AnsVal將從Raiobutton得到它的值。

+0

你想要在視圖中使用組合模型? –

+0

是的,以便我可以在視圖中重新指定它。 – user952072

+1

您可以使用Neel Bhatt的建議。 –

回答

2

使下面的組合類,我不知道這是完美的或不..任何建議是可以接受的。

public class QuestionAnswerViewModel 
{ 
    public Question Question {get;set;} 
    public ICollection<UserAnswer> Answers {get;set;} 
} 
+0

我也必須設置[Key] public int QuestionIdMap {get;組; }在你的例子中。但我怎麼能在視圖中呈現 – user952072

+0

只需綁定「QuestionAnswerViewModel」,如下所示: - – Neel

+0

@model MyProject.Web.ViewModels.QuestionAnswerViewModel – Neel

0

您想創建一個表示組合模型對象的ViewModel。這使得事物保持清潔,模型就是這樣,模型,傳遞給視圖的東西可以作爲模型,但是在很多情況下,ViewModel的概念將使設計更容易,同時保持代碼鬆散耦合和清潔。這也可以讓視圖中不重要的東西超出等式,即模型中的特定屬性,例如可能不應將CreatedDate傳遞給視圖,尤其是因爲視圖請求將傳回值爲空,因爲它不是在視圖中使用,因此不會在回發中填充。這可能會導致您使用CreatedDate的空值更新數據庫,因爲它沒有在View中使用。

也許你的解決方案中有模型類庫?如果你這樣做,創建另一個名爲MyNamespace.Web.ViewModels的類庫或類似的東西。你也應該看看使用像AutoMapper這樣的工具,它將查看ViewModel請求填充到Controller,並在View上填充模型回發給控制器。