Semi-automatic delete of a record in MVC isn’t working as intended

On an older project I'm able to delete records from the list on the Index view:

@foreach (var item in Model) { <tr> <td id="delete"> @Html.ActionLink(" ", "Delete, new { id = item.Id }, new { onclick = "return confirm('Are you sure you want to delete this record?');", @class = "delete-button" }) 

The Action in the Controller looks like this:

public ActionResult Delete(int id) { User user = db.Users.Find(id); if (user == null) { // not gonna show ReportError because it's irrelevant here return ReportError("User not found"); } else { db.Users.Remove(user); db.SaveChanges(); return RedirectToAction("Index"); } } 

This works as you'd expect it to. When you click on the link, you get a javascript confirmation box asking if you want to delete. When you click yes, it deletes the record and reloads the page.

My problem is this implementation doesn't seem to be working on my other project which uses my ASP.NET Web Api 2 web service to work with the data.

@Html.ActionLink(" ", "Delete", new { id = item.Id }, new { onclick="return confirm('Are you sure you want to delete this User?');", @class = "delete-button" }) private async Task<ActionResult> Delete(int id) { string url = String.Format("api/user/{0}", id); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(ServiceURL); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.DeleteAsync(url); return RedirectToAction("Index"); } } 

What's happening here is that MVC is instead trying to navigate to ~/User/Delete/{id} which clearly it isn't written to do.

I don't have a Task in the controller for delete other than what I've shown here so what's going on?

by ortund via /r/csharp

Leave a Reply