Coding Flow
Coding Flow

Reputation: 21881

MVC 3 2 models in a view

I am new to MVC (i.e. the last few days) and i would like to know if what i have done is the best way.

I have a view that is a combination of an insert item form with a list details form underneath for a particular entity. As such i kind of need 2 models for the page in order to avoid doing things like @Html.LabelFor(model => model.FirstOrDefault().EventTypeID, "Event Type").

What i have done is set the model to be Tuple<IEnumerable<Event>,Event> that way i have both the single item and the collection of items. Can anyone suggest a less hacky alternative or is this the best way of doing this?

Upvotes: 2

Views: 335

Answers (3)

Arnold Zokas
Arnold Zokas

Reputation: 8590

I suggest you create a ViewModel that would contain both objects you want to pass.

public class NewEventViewModel
{
    public Event NewEvent { get; set; }
    public Event EventDetails { get; set; }
}

You could also use ViewBag, but it is not strongly typed so you would not get IntelliSense.

Upvotes: 1

themarcuz
themarcuz

Reputation: 2583

I would create a Model object just for the view, with 2 properties, one for the single entity and one for the collection, and then you can pass this composed object as the model for the view

Upvotes: 0

dknaack
dknaack

Reputation: 60556

There are 2 solutions.

  • You should create a different View Model Class (a simple class with both models as properties)
  • You can assign it to the ViewBag.Model1 ... ViewBag.Model2 ... But this is dynamic so you will have no intellisense and you can get errors at runtime.

You should use a ViewModel like this

public class ViewModel
{
    public TypeOfYourModel MyModel1 { get; set; }
    public TypeOfYourModel MyModel2 { get; set; }
}

Upvotes: 5

Related Questions