views:

12

answers:

1

Ive got projects and devices which are linked to each other in a many-to-many relation. On creation of a project the user gets a list of available devices to link to the project using checkboxes. The controller code for create is shown below.

I am using ASP MVC with ActiveRecord.

public ActionResult Create()
  {
      ViewData["devices"] = Models.User.Find(SessionVariables.AuthenticatedUser.Id).Devices;
      return View();
  }

  [HttpPost]
  public ActionResult Create(FormCollection collection)
  {
     try
     {
         Project project = new Project();

         TryUpdateModel(project, _updateableFields);

         project.User = SessionVariables.AuthenticatedUser;
         project.SaveAndFlush();

         var c = collection["devices"];
         string[] arr1 = ((string)c).Split(',');
         int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));

         foreach (int i in arr2)
         {
             Device d = Device.Find(i);
             d.Projects.Add(project);
             d.SaveAndFlush();
         }

         return RedirectToAction("Index");

     }
     catch(Exception e)
     {
        return RedirectToAction("Index", "Error");
     }
  }

For deleting a project:

public ActionResult Delete(int id, FormCollection collection)
  {
     if (!Project.Exists(id)) return RedirectToAction("Index/1", "Error");

     try
     {
        Project project = Project.Find(id);
        if (project.User.Id != SessionVariables.AuthenticatedUser.Id) return RedirectToAction("Index/1", "Error");

        project.DeleteAndFlush();

        return RedirectToAction("Index", "Project");
     }
     catch
     {
        return RedirectToAction("Index", "Error");
     }
  }

Creating the project with the device relation works. What I am trying to do now is making a edit page which shows the entire list of all available devices where the checkboxes of the devices that are linked to a project are checked. I don't know how to check if a relation exists and show the checkbox as checked.

Also how do I update the table once a device is unchecked. In other words, how do I delete it in the edit mode?