1

I'm trying to make a delete functionality in my program. I followed this tutorial. But when I tried deleting this error came out.

error message

here is my class from model for delete.

        public bool deleteAccount(int Id) {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("", conn)) {
            comObj.CommandText = "DELETE FROM account WHERE userId = @userId";
            comObj.Parameters.AddWithValue("@userId", Id);
            conn.Open();
            int res = comObj.ExecuteNonQuery();
            if (res >= 1)
            {

                return true;

            }
            else
            {

                return false;
            }
        }
    }

My delete action controller

public ActionResult deleteAccount()
    {
        return View();
    }

    public ActionResult deleteAccount(int id)
    {

        try
        {
            var databaseModel = new database();
            if (databaseModel.deleteAccount(id)) {
                ViewBag.AlertMsg = "Employee details deleted successfully";
            }
            return RedirectToAction("GetAllEmpDetails");
        }
        catch {
            return View();
        }

full stack trace

[AmbiguousMatchException: The current request for action 'deleteAccount' on controller type 'accountController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult deleteAccount() on type directory.Controllers.accountController System.Web.Mvc.ActionResult deleteAccount(Int32) on type directory.Controllers.accountController] System.Web.Mvc.ActionMethodSelectorBase.FindActionMethod(ControllerContext controllerContext, String actionName) +113 System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +54 System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +203 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +136 System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465 System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Hope someone can help me.

| EDIT |

I tried other tutorials a while ago. and I also tried adding [HttpPost] but the ID being passed to the URL is always 0. so I tried displaying my userId

acc.userName = rdr["userId"].ToString();

and every ID I get is 0

chemical_elii
  • 155
  • 1
  • 11
  • If I recall this correctly, the only way to disambiguate the method names is to set different (Get, Post) attributes. MVC doesn't like the same names on the controllers. So... What you can do instead is for one method pass in an object instead, the object affects the behavior, and MVC will automatically create that model on entry to that method. This is known as Strongly typed binding. Of course you could always rename the methods if you must keep three of the similar methods. – JWP Jun 01 '17 at 17:05
  • Add `[HttpPost]` above your second delete method. – Zach M. Jun 01 '17 at 17:06
  • 3
    Side note - do not use empty catch blocks that do nothing. You will never know if there is an error because you swallow your exception. If you are going to catch the exception then you should handle it or log it at the very least. – Igor Jun 01 '17 at 17:13
  • how is this a possible duplicate of that? – chemical_elii Jun 01 '17 at 17:40
  • How is it not? In your question and that one, you have two action methods with the same name that need to be distinguished by either changing the name of changing the HTTP Method associated with them. – mason Jun 01 '17 at 17:52

5 Answers5

3

Look at the resource below hope it helps, Also i think you should start looking at Entity Framework for your Data Access.

You can do something like in this example

// GET: /Movies/Delete/5
public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

// POST: /Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Movie movie = db.Movies.Find(id);
    db.Movies.Remove(movie);
    db.SaveChanges();
    return RedirectToAction("Index");
}

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-details-and-delete-methods

Frank Odoom
  • 1,545
  • 18
  • 19
0

The second controller must have the request method like:

    public ActionResult deleteAccount()
    {
        return View();
    }
    [HttpPost]
    public ActionResult deleteAccount(int id)
    {

        try
        {
            var databaseModel = new database();
            if (databaseModel.deleteAccount(id)) 
            {
                ViewBag.AlertMsg = "Employee details deleted successfully";
            }
            return RedirectToAction("GetAllEmpDetails");
        }
        catch 
        {
            return View();
        }
    }
Antonio
  • 251
  • 5
  • 11
0

By default the action method stands as Get if we don't explicitly specify it is Get or Post, so when you try to call either one it ends up confused on which action method was supposed to call (with parameter or without parameter), you need to specify which is for Get and which is for Post like:

[HttpGet]
public ActionResult deleteAccount()
{
    return View();
}

[HttpPost]
public ActionResult deleteAccount(int id)
{

    try
    {
        var databaseModel = new database();
        if (databaseModel.deleteAccount(id)) {
            ViewBag.AlertMsg = "Employee details deleted successfully";
        }
        return RedirectToAction("GetAllEmpDetails");
    }
    catch {
        return View();
    }
}

Hope it helps!

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

You can't have the same HTTP verb for the same action name. In other words, having HttpGet for the same action name, even an overload, isn't possible.

Change one or your action methods to a different HTTP action verb...

[HttpGet]
public ActionResult deleteAccount()
{
    //..
}

[HttpPost]
public ActionResult deleteAccount(string country)
{
    //..
}
Karan Singh
  • 876
  • 1
  • 6
  • 12
0

if you are using WebAPI2, you can specify your route prefix and set your controller name to Delete (without the DeleteXXX)

For example,

[RoutePrefix("api/Account")]
public class AccountController : ApiController
    {

        public IHttpActionResult Delete(Guid id)
        {
        }


        public IHttpActionResult Delete()
        {
        }    
   }
hongguan
  • 520
  • 2
  • 12