0

What are some ways I can delete an item from a collection? (I am using MVC 4 and EF.)

As an example:

public class Birthday
{
    public string Name { get; set; }

    public virtual ICollection<Gift> Gifts { get; set; }
}

public class Gift
{
    public string Name { get; set; }

    public double Price { get; set; }
}

I'm using Editing a variable length list, ASP.NET MVC 2-style to create a dynamic list of Gifts.

The example is shows how to "Delete" a row. This will delete the row from the page and the correct Gifts are sent to the controller.

When I update the Birthday / Gifts everything new is updated properly, but anything deleted is still there.

So my question is what are some preferred ways to remove Gifts?

Two ways I've thought of already:

  1. Get a Birthday from the DB and compare the Gifts removing as needed. I don't love this idea because it seems heavy handed.
  2. Use WebApi / Ajax and delete the Gift from the list and the DB when the user pushes the delete link. I like this better than #1 but does this put too much business logic in the presentation layer?

I'm guessing that other people have had this similar problem and have a clever solution I haven't thought of yet.

Thanks in advance!

2 Answers 2

2

Make a Gifts api controller. Let it have a Delete method accepting an Id of whatever type your Id is. And do something like this in it:

public class GiftsController: ApiController
{
     public void Delete(Guid Id)
     {
           var context = new MyContext();
           var giftToDelete = context.Gifts.FirstOrDefault(g=> g.Id == Id);
           if(giftToDelete != null)
           {
                 context.Gifts.Remove(giftToDelete);
                 context.SaveChanges();
           }
     }
}

Make sure you make a DELETE request to this api in your JS delete function. You may also replace the body of this method with some Service.DeleteGift(Id) if you're too concerned about doing things in the right place.

0
0

Like this:

public class ValuesController : ApiController
    {
        private List<string> list = new List<string>{"Item1","Item2","Item3","Item4","Item5"};

        // DELETE api/values/5
        public List<string> DeleteItem(int id)
        {
            list.Remove(list.Find((i => i.ToString().Contains(id.ToString()))));
            return list;
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.