ASP.NET MVC使用确认删除操作链接

Pin*_*inu 10 asp.net asp.net-mvc

      <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>
Run Code Online (Sandbox Code Playgroud)

在Global.asax.cs中

routes.MapRoute(
               "DeleteUser",
               "Account.aspx/DeleteUser/{uname}",
               new { controller = "Account", action = "DeleteUser", uname = "" }
           );
Run Code Online (Sandbox Code Playgroud)

在ActionContorller.cs中

public ActionResult DeleteUser(string uname)
{
   //delete user
}
Run Code Online (Sandbox Code Playgroud)

正在传递的控制器中uname的值是空字符串("").

Dar*_*rov 32

试试这样:

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

然后确保生成的链接正确:

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

另请注意,建议不要使用普通的GET动词来修改服务器上的状态.

这是我建议你的:

[HttpDelete]
public ActionResult DeleteUser(string uname)
{
   //delete user
}
Run Code Online (Sandbox Code Playgroud)

并在视图中:

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

并在一个单独的JavaScript文件中:

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

您还可以考虑添加防伪令牌以保护此操作免受CSRF攻击.