title: Changing from using Model to ViewModel
body: <p>I have an index page that lists all users. This has the following in the Users controller - </p>
  
  <pre><code> public ViewResult Index()
          {
              return View(userRepository.AllIncluding(user =&gt; user.Roles));
          }
  </code></pre>
  
  <p>and then the view starts with</p>
  
  <pre><code>@model IEnumerable&lt;TRS.Models.User&gt;
  </code></pre>
  
  <p>and then uses </p>
  
  <pre><code> @foreach (var item in Model) {
  </code></pre>
  
  <p>to loop through all users in my model.</p>
  
  <p>I now need to change my model to a ViewModel that contains both the User model and an extended UserDetails model.</p>
  
  <p>I have changed my Index view to use the view model -</p>
  
  <pre><code>@model IEnumerable&lt;TRS.ViewModels.RegisterViewModel&gt;
  </code></pre>
  
  <p>But I don't know how I should be going about filling the ViewModel in my controller - </p>
  
  <pre><code>public ViewResult Index()
          {
  
              var viewModel = new RegisterViewModel
              {
                  UserName = "???"
                  FirstName = "???"
                  LastName = "???"
              };
  
              return View(viewModel);
          }
  </code></pre>
  
  <p>I assume I need to create an instance of the view model and then pass it to the view. But I don't understand how I can get data against each individual item. I'll obviously need to get all data for all users here and then loop through them in my view. Any ideas what I should be going in the controller above? What should replace the "???" with that will fill the viewModel with all the data? Or is this the wrong approach?</p>
  
  <p>Thanks</p>
  
  <p>Edit - Models added - </p>
  
  <pre><code>public class User
      {
          [Key]
          public string UserName { get; set; }
  
          public virtual ICollection&lt;Role&gt; Roles { get; set; }
          public virtual UserDetails UserDetails { get; set; }
  }
  
  
   public class UserDetails
      {
  
          [Key]
          public string UserName { get; set; }
          public string Firstname { get; set; }
          public string Lastname { get; set; }
  
          [Required]
          public virtual User User { get; set; }
  }
  </code></pre>
  
  <p>Edit - From View -</p>
  
  <pre><code>&lt;td&gt;
                  @foreach (Role role in item.Roles){
                  @role.RoleName &lt;br /&gt;
      }&lt;/td&gt; 
  </code></pre>