I’m trying to figure out how to have an edit function and a delete function from the same page in my application. At the moment my controller looks like this:
[HttpPost]
public ActionResult Edit(CodeTagViewModel codeTagViewModel, FormCollection collection)
{
if (ModelState.IsValid)
{
List<Tag> tagsToAdd = new List<Tag>();
codeTagViewModel.Tags = db.Tags.ToList();
foreach (Tag tag in codeTagViewModel.Tags)
{
if (collection[tag.TagID.ToString()].ToString().Contains("true"))
{
tagsToAdd.Add(tag);
}
}
codeTagViewModel.SelectedTags = tagsToAdd;
Code code = db.Code.Find(codeTagViewModel.CodeID);
MapModelToCode(codeTagViewModel, code);
db.Entry(code).State = EntityState.Modified;
db.SaveChanges();
return View(codeTagViewModel);
}
return RedirectToAction("Index");
}
[HttpPost, ActionName("Delete")]
public ActionResult Edit(CodeTagViewModel codeTagViewModel, FormCollection collection)
{
if (ModelState.IsValid)
{
List<Tag> tagsToAdd = new List<Tag>();
codeTagViewModel.Tags = db.Tags.ToList();
foreach (Tag tag in codeTagViewModel.Tags)
{
if (collection[tag.TagID.ToString()].ToString().Contains("true"))
{
tagsToAdd.Add(tag);
}
}
codeTagViewModel.SelectedTags = tagsToAdd;
Code code = db.Code.Find(codeTagViewModel.CodeID);
MapModelToCode(codeTagViewModel, code);
db.Code.Remove(code);
db.SaveChanges();
return View(codeTagViewModel);
}
return RedirectToAction("Index");
}
And I’ve got the two buttons in my Edit view:
<p>
<input type="submit" value="Save" />
</p>
<p>
<input type="submit" value="Delete" />
</p>
And my view model looks like this:
public class CodeTagViewModel
{
public List<Tag> Tags { get; set; }
public List<Tag> SelectedTags { get; set; }
public int CodeID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime DateAdded { get; set; }
public DateTime LastUpdated { get; set; }
public string Project { get; set; }
public string CMS { get; set; }
public int DotNetVersion { get; set; }
public string Dependencies { get; set; }
public string Author { get; set; }
public string CodeFile { get; set; }
public string TFSLocation { get; set; }
}
At the moment the delete button is doing nothing, it’s not hitting the code at all.
I’m new to MVC and trying to figure out how it handles all of the background stuff so any help would be greatly appreciated.
EDIT: I’ve also looked into the routing aspect and put in:
//
// POST: /Code/Edit/5
Above the delete function (it’s the same as the one for the edit) and still nothing.
That’s because both the
EditandDeletebutton both do the same thing, they simply post the form. So they will always post to the same place.You should change your delete button to be an
ActionLink, then change yourDeletemethod to be aHttpGet, pass in the ID of the item you want to delete and then retrieve and delete it.Like this:
Then in your action method:
Otherwise, you’d have to use Javascript to automatically change the post URL of the form depending on which button was clicked, which is nasty.