Marc
Marc

Reputation: 67

ASP MVC - many to many relationship

I have honestly looked for over an hour for a satisfactory answer to this question. So it's not that I haven't found answers, just not ones I feel are completely correct. Which may just mean that I'm looking for a silver bullet that doesn't exist.

In asp mvc with an EF (code first) model that includes a many to many relationship, how do I bind that relationship to checkboxes and then propagate those changes elegantly to my database.

If the view is only returning the values for checkboxes that were checked, then I no longer know which values were previously checked. Do I pull back the original object again and then compare the two? It feels dirty, probably because I'm so used to letting the EF magic manage the properties that have changed on an object.

I've already have a dirty version that I'm not happy with.

    [HttpPost]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            // TODO: Add insert logic here
            Program p = _programRep.GetByID(id);

            //manually update properties
            //change to model binding later


            EditPolicies(ref p, collection["SelectedPolicies"].ToString().Split(','));

            _programRep.Save(p);

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    private void EditPolicies(ref Program c, string[] selectedvals)
    {
        //I could do comparison logic here 
        int count = c.Policies.Count;
        for (int i = 0; i < count; i++)
        {
            c.Policies.Remove(c.Policies.ElementAt(0));
        }

        for (int i = 0; i < selectedvals.Count(); i++)
        {
            Policy g = _policyRep.GetByID(int.Parse(selectedvals[i]));
            c.Policies.Add(g);
        }
    }

Upvotes: 4

Views: 709

Answers (1)

John Farrell
John Farrell

Reputation: 24754

I'm not quite sure how you expect this to work so I don't know what you are looking for but this is the correct way and by design.

There are a lot of modeling cases. Wish I saved the link I found with the perfect example where the removal of an object from a collection simply means a relationship is missing and not that a row needs to be deleted.

The only elegance I would add is something like:

 c.Policies.AddRange(_policyRep.GetByIDs(selectedvals[i]));

Upvotes: 1

Related Questions