athira k

athira k

  • NA
  • 140
  • 53.8k

how to delete multiple entries from db by passing id in mvc

Apr 19 2017 3:18 AM
I have a doubt in mvc that how can I delete multiple entries from a table by passing id. that is to group different entries of postname under the same name and when deleting by hiting on the delete link it will show the confirmation page to delete. In the HttpGet method of delete I have written the code and will work
 
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Mapping mapping = await db.Mappings.FindAsync(id);
var ListItems = (from ap in db.Mappings
join a in db.Masters on ap.MasterId equals a.ID
join p in db.Posts on ap.PostId equals p.Id
select new MappingList
{
id = ap.Id,
Masterid = ap.AgentId,
postid = ap.PostId,
name = a.Name,
Postname = p.PostName
}).Where(r => r.Masterid == id).ToList();
var grp = ListItems.GroupBy(r => r.Masterid).Select(r => new MappingList
{
Masterid = r.Key,
id = r.Key,
PostNames = string.Join(" , ", r.Select(g => g.Postname)),
name = ListItems.FirstOrDefault(q => q.Masterid == r.Key).name
}).ToList();
if (grp == null)
{
return HttpNotFound();
}
return View(grp);
}
 
Here Mapping is the table and wants to delete entries from this table.MappingList is a modelclass.
In the delete view page have given
@model IEnumerable<A.Models.MappingList>   and get the result I need . But when I click on the delete confirm button  I need to remove value of  grp, so that the entry will get removed and save to Mapping table. this is the section that I am not able to do 
 
 
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Mapping mapping = await db.Mappings.FindAsync(id);
db.Mappings.Remove(mapping);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
 Can anyone please help me to find the solution how to delete the entry in Mapping table by passing id ??
 

Answers (7)