0

Untill now in C# MVC3 i only had to use one controller which used only one model.

But now i think i need access to two models in my controller. I'm wondering if this is allowed in the MVC pattern?

I have a ProfileController. The ProfileController shows the profile info of a user obviously. But there's also some other data that i wish to show, like the groups a user created. For that i also have a GroupsModel.

How am i supposed to get both data from one controller?

2 Answers 2

3

How am i supposed to get both data from one controller?

By using a view model:

public class MyViewModel
{
    public ProfileModel Profile { get; set; }
    public GroupsModel Groups { get; set; }
}

and then passing this view model to the view:

public ActionResult ShowProfile()
{
    var model = new MyViewModel();
    model.Profile = ...
    model.Groups = ...
    return View(model);   
}

And now your view will be strongly typed to the view model:

@model MyViewModel

and you can display information:

@Html.DisplayFor(x => x.Profile.SomeProperty)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, a good explanation. Just one thing i want to make sure though. Can i put this ViewModel in the "Models" folder too? Or is it better to create a separate folder called "ViewModels" ?
@w00 - It's entirely up to you in that respect, personally I tend to keep all my models in the same folder (irrespective of View/Data). Unless of course there comes a need to separate e.g. layered architecture.
This is a useful answer because it illustrates the flexibility of the @model keyword. Being able to pass any type of object as the Model means you can pass structs, which in some cases may be slightly preferable for performance.
1

Assuming that you aren't putting too much into a single view/controller, why not compose a simple view model which has the data you need?

public class ProfileInfo
{
   public Person Person
   {
      get;
      set;
   }

   public List<Group> Groups
   {
       get;
       set;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.