Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Delete Action Link with confirm

      <td>
  <%= Html.ActionLink("Delete", "DeleteUser", new RouteValueDictionary(new {uname=item.UserName}), new { onclick = "return confirm('Are you sure you want to delete this User?');" }) %>
    </td>

In Global.asax.cs

routes.MapRoute(
               "DeleteUser",
               "Account.aspx/DeleteUser/{uname}",
               new { controller = "Account", action = "DeleteUser", uname = "" }
           );

In ActionContorller.cs

public ActionResult DeleteUser(string uname)
{
   //delete user
}

the value of uname in the controller is being passed is empty string("").

like image 573
Pinu Avatar asked Mar 28 '11 18:03

Pinu


1 Answers

Try like this:

<%= Html.ActionLink(
    "Delete", 
    "DeleteUser", 
    "Account",
    new { 
        uname = item.UserName 
    }, 
    new { 
        onclick = "return confirm('Are you sure you want to delete this User?');" 
    }
) %>

Then make sure that the generated link is correct:

<a href="/Account.aspx/DeleteUser/foo" onclick="return confirm(&#39;Are you sure you want to delete this User?&#39;);">Delete</a>

Also note that using a plain GET verb for an action that modifies the state on the server is not recommended.

Here's what I would recommend you:

[HttpDelete]
public ActionResult DeleteUser(string uname)
{
   //delete user
}

and in the view:

<% using (Html.BeginForm(
    "DeleteUser", 
    "Account", 
    new { uname = item.UserName }, 
    FormMethod.Post, 
    new { id = "myform" })
) { %>
    <%= Html.HttpMethodOverride(HttpVerbs.Delete) %>
    <input type="submit" value="Delete" />
<% } %>

and in a separate javascript file:

$(function() {
    $('#myform').submit(function() {
        return confirm('Are you sure you want to delete this User?');
    });
});

You might also consider adding an anti forgery token to protect this action against CSRF attacks.

like image 170
Darin Dimitrov Avatar answered Oct 09 '22 00:10

Darin Dimitrov