2012-10-30 60 views
1

我試圖在單個cshtml文件中使用多個模型。我的代碼是:html中的多個模型

@model CostumeContest.Models.VoteModel 
@{ 
    ViewBag.Title = "Vote"; 
} 


<h2 style="color: #B45F04">Vote Receipt</h2> 
<b>Your Name:</b> @Model.VoterName 
<br /> 
<b>Your Vote for Best Costume: </b>@Model.BestName 
<br /> 
<b>Your Vote for Most Creative Costume:</b> @Model.CreativeName 
<br /> 

<h2 style="color: #B45F04">Vote Summary</h2> 

//@model CostumeContest.Models.VoteResult this is giving me problems when not commented out 
<h3 style="color: #B45F04">Best Costume</h3> 


<h3 style="color: #B45F04">Most Creative Costume</h3> 

我在上面做什麼錯,更重要的是,我該如何解決我的問題?謝謝。

+0

這沒有任何意義。你的行爲會是什麼樣子? – SLaks

+0

[ASP MVC 3中的一個視圖中的兩個模型]的副本(http://stackoverflow.com/questions/5550627/two-models-in-one-view-in-asp-mvc-3/7558510) – Bobson

回答

1

最好的辦法是製作一個視圖模型,其中包含您需要的所有內容。因爲你的代碼是稀疏的,我會採取瞎猜:

namespace CostumeContest.Models 
{ 
    public class MyViewModel 
    { 
     public VoteModel VoteModel { get; set; } 
     public VoteResult VoteResult { get; set; } 
    } 
} 

你的第一個@model行然後更改爲:

@model CostumeContest.Models.MyViewModel

很明顯,你會更改名稱這個類對你來說是有意義的。然後,您將創建一個MyViewModel實例,使用它設置VoteModelVoteResult屬性,並將MyViewModel的實例發送到視圖,而不是VoteModel

+0

這是正是我所期待的。感謝Gromer –

0

您應該創建一個帶有其他兩個類的屬性的外部模型類。

1

使用Tuple來保存這兩個對象。

@model Tuple<VoteModel, VoteResult> 

Gromer的答案是一個更好的設計,但這是一個簡單的解決方案。