title: How can i attach existing model(device) data to another model(user) data in mvc asp.net
body: <p>I am creating a system where when a user is created a device can be assigned to that user.  I am doing this with a dropdown and while the dropdown is populated with the list of devices, it does not update the user with that device.  Multiple users can use the same device and i want to avoid hard coding as the information is already on the database.</p>
  
  <p>I am doing this through ef code first any other suggestions will be taken into account.  Im really just focused on getting this to work so i am open to suggestions. I also want to get this working with edit, however im assuming the solution will fix both create and edit, if i use similar code.</p>
  
  <p>I have been using a viewmodel to display the devices on the index page.  The current users on the db show their allocated devices so i know that works, but i had to manually assign the devices in the table data.</p>
  
  <p><strong>PatientController.cs (users are also known as patients)</strong></p>
  
  <pre><code>namespace FaceToFaceWebsite.Controllers
  {
      public class PatientController : Controller
      {
          private F2FData db = new F2FData();
  
          public ActionResult Index()
          {
              var viewModel = db.Users
                  .Select(u =&gt; new UserDeviceViewModel() 
              { 
                  User = u,
                  Device = u.Device
  
               }).ToList();
  
              return View(viewModel);
          }
  
  
          public ActionResult Create()
          {
              ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name");
  
              return View();
          }
  
          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Create([Bind(Include = "UserID,CodeName,UseBriefInstructions,DeviceID,Name")] User user, Device device)
          {
              if (ModelState.IsValid)
              {
  
                  db.Users.Add(user);
                  db.Devices.Attach(device);
                  db.SaveChanges();
                  return RedirectToAction("Index");
              }
              return View(user);
          }
  </code></pre>
  
  <p><strong>User.cs (in another project, but in the same solution)</strong></p>
  
  <pre><code>namespace FaceToFace.Model
  {
      public class User
      {
          public int UserID { get; set; }
          public string CodeName { get; set; }
          public bool UseBriefInstructions { get; set; }
          public ICollection&lt;RegimeItem&gt; RegimeItems { get; set; }
          public Device Device { get; set; }
          public virtual ICollection&lt;Grading&gt; UserGradings { get; set; }
          public User()
          {
              this.RegimeItems = new List&lt;RegimeItem&gt;();
              Device = new Device();
          }   
      }
      public class RegimeItem
      {
          public int RegimeItemID { get; set; }
          public Exercise RegimeExercise { get; set; }
      }
  }
  </code></pre>
  
  <p><strong>Device.cs (in another project, but in the same solution)</strong></p>
  
  <pre><code>namespace FaceToFace.Model
  {
      public class Device
      {
          public int DeviceID { get; set; }
          public string Name { get; set; }
      }
  }
  </code></pre>
  
  <p><strong>UserDeviceViewModel.cs</strong></p>
  
  <pre><code>namespace FaceToFaceWebsite.Models
  {
      public class UserDeviceViewModel
      {
          public Device Device { get; set; }
          public User User { get; set; }
          public IList&lt;SelectListItem&gt; Name { get; set; }
      }
  }
  </code></pre>
  
  <p><strong>View/Patient/Create.cshtml</strong></p>
  
  <pre><code>    @model FaceToFace.Model.User
  
      @{
          ViewBag.Title = "Create";
      }
  
      &lt;h2&gt;Create&lt;/h2&gt;
  
      @using (Html.BeginForm()) {
          @Html.AntiForgeryToken()
          @Html.ValidationSummary(true)
  
          &lt;fieldset&gt;
              &lt;legend&gt;User&lt;/legend&gt;
  
              &lt;div class="editor-label"&gt;
                  @Html.LabelFor(model =&gt; model.CodeName)
              &lt;/div&gt;
              &lt;div class="editor-field"&gt;
                  @Html.EditorFor(model =&gt; model.CodeName)
                  @Html.ValidationMessageFor(model =&gt; model.CodeName)
              &lt;/div&gt;
  
              &lt;div class="editor-label"&gt;
                  @Html.LabelFor(model =&gt; model.Device.Name, "Device")
              &lt;/div&gt;
              &lt;div class="editor-field"&gt;
              @Html.DropDownListFor(model =&gt; model.Device.DeviceID, (IEnumerable&lt;SelectListItem&gt;)ViewBag.DeviceID)
  
              &lt;/div&gt;
  
              &lt;div class="editor-label"&gt;
                  @Html.LabelFor(model =&gt; model.UseBriefInstructions)
              &lt;/div&gt;
              &lt;div class="editor-field"&gt;
                  @Html.EditorFor(model =&gt; model.UseBriefInstructions)
                  @Html.ValidationMessageFor(model =&gt; model.UseBriefInstructions)
              &lt;/div&gt;
  
              &lt;p&gt;
              &lt;input type="submit" value="Create" /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  
  &lt;div&gt;
      @Html.ActionLink("Back to List", "Index")
  &lt;/div&gt;
  </code></pre>
  
  <p>I believe the problem lies with what ive been doing in the Controller, and after many tries i cannot get the create function to assign a user to a device from the db so any help would be greatly appreciated.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p><strong>PatientController.cs</strong></p>
  
  <pre><code>private void PopulateDeviceChoices(UserDeviceViewModel model)
  {
      model.DeviceChoices = db.Devices.Select(m =&gt; new SelectListItem
      {
          Text = m.Name,
          Value = m.DeviceID
      });
  }
          //
          // GET: /Patient/
          public ActionResult Index()
          {
              //var viewModel = new List&lt;FaceToFaceWebsite.Models.UserDeviceViewModel&gt;();
              var viewModel = db.Users
                  .Select(u =&gt; new UserDeviceViewModel()
              {
                  User = u,
                  Device = u.Device
  
              }).ToList();
  
  
              return View(viewModel);
          }
  
  
  
          public ActionResult Create(UserDeviceViewModel model, User user)
          {
              ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name");
  
  
              var device = db.Devices.Find(model.DeviceId);
              user.Device = device;
  
              PopulateDeviceChoices(model);
              return View(model);
          }
  
          //
          // POST: /Patient/Create
          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Create(User user, Device device, UserDeviceViewModel model)
          {
              if (ModelState.IsValid)
              {
  
                  db.Users.Add(user);
                  db.Devices.Attach(device);
                  db.SaveChanges();
                  return RedirectToAction("Index");
              }
              PopulateDeviceChoices(model);
              return View(model);
          }
  </code></pre>
  
  <p>I have made the changes as Chris' suggestions, however i dont think i have translated them correctly, as i am getting an error at <code>Value = m.DeviceID</code>   which is telling me <code>Cannot implicitly convert type 'int' to 'string'</code></p>
  
  <p>I have got it working however, i am getting two sets of user input rows on the view, it also does not allow me to assign a device to a user still. <img src="https://i.stack.imgur.com/Lagqv.jpg" alt="image of create view below"></p>
  
  <p><strong>Update 2 (Stephens suggestions)</strong></p>
  
  <p><strong>PatientController.cs</strong></p>
  
  <pre><code>public ActionResult Create()
          {
              UserDeviceCreateViewModel model = new UserDeviceCreateViewModel();
              ConfigureViewModel(model);
              return View(model);
          }
  
          public ActionResult Create(UserDeviceCreateViewModel model, User user, Device device)
          {
              if (!ModelState.IsValid)
              {
                  ConfigureViewModel(model);
                  return View(model);  
              }
              db.Users.Add(user);
              db.SaveChanges();
              return RedirectToAction("Index");
  
          }
  </code></pre>