1

I'm trying to use multiple models in a single cshtml file. The code I have is:

@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> 

What is wrong with what I'm doing above, and more importantly, how can I solve my issue? Thank you.

Sean Smyth
  • 1,509
  • 3
  • 25
  • 43
  • That doesn't make any sense. What would your action look like? – SLaks Oct 30 '12 at 20:13
  • Duplicate of [Two models in one view in ASP MVC 3](http://stackoverflow.com/questions/5550627/two-models-in-one-view-in-asp-mvc-3/7558510) – Bobson Oct 30 '12 at 20:25

3 Answers3

1

Best bet is to make a view model that has everything you need in it. Since your code is sparse, I'm going to take a shot in the dark:

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

Then change your first @model line to:

@model CostumeContest.Models.MyViewModel

Obviously, you'd change the name of the class to something that makes sense for you. You would then create a MyViewModel instance, set the VoteModel and VoteResult properties with it, and send the instance of the MyViewModel to the view, not a VoteModel.

Gromer
  • 9,861
  • 4
  • 34
  • 55
1

Use a Tuple to hold both objects.

@model Tuple<VoteModel, VoteResult>

Gromer's answer is a better design, but this is an easy solution.

Bobson
  • 13,498
  • 5
  • 55
  • 80
0

You should create a single outer model class with properties holding the other two classes.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964