c# - 不会调用 HttpPost

标签 c# asp.net asp.net-mvc asp.net-mvc-routing

我已经在这里待了一个小时了,但我不知道我做错了什么。

我得到以下 ActionLink:

@Html.ActionLink("Remove", "RemoveActivity", "Dashboard", new { id = a.Id },htmlAttributes: null)

这针对我的 DashboardController 中的以下方法:

[HttpPost]
public ActionResult RemoveActivity(int id)
{
    activityRepo.Delete(activityRepo.GetById(id));

    return RedirectToAction("ActivityDetails");
}

由于某种原因返回此错误:

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Dashboard/RemoveActivity/564

数据库中确实存在Id为564的表行。它在几个小时前工作。 任何帮助表示赞赏。我很无知!

编辑:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace HaarlemFestival_Web
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
}

最佳答案

@Html.ActionLink()生成 <a>生成 GET 而不是 POST 的标签。您需要包含一个 <form>元素并将值提交给您的 POST 方法

@using (Html.BeginForm("RemoveActivity", "Dashboard", new { id = a.Id }))
{
    <input type="submit value="Remove" />
}

如果您希望视觉上看起来像链接,您可以将提交按钮的样式设置为链接

我还建议您添加 @Html.AntiForgeryToken() <form> 中的方法并添加 [ValidateAntiForgeryToken]将属性添加到您的方法中以防止 CSRF 攻击。

您还应该考虑验证当前用户是否有权删除该记录。

请注意,由于您的方法正在更改数据,因此它应该是一个 POST,所以不要试图删除 [HttpPost]从您的方法中提取属性,以便链接有效。

关于c# - 不会调用 HttpPost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49808069/

相关文章:

asp.net - ASP.NET MVC 中的模拟 User.Identity

c# - 如何在长名称的文件夹中创建文件。 (避免 PathTooLongException)

c# - 将查询参数绑定(bind)到 ASP.NET Core 中的模型

c# - 我们可以在 Entity Framework 中使用没有主键的表吗?

c# - 在 Lua 中处理 StackOverflowException

c# - asp.net 下拉列表和 View 状态

asp.net - "X-UA-Compatible IE=edge" header 不应该覆盖 IE10 中的 "Display intranet sites in Compatibility View"吗?

c# - 如何使用不同的参数在同一 Controller 中调用不同的 GET 方法?

c# - 如何安排在我的 MVC 网络应用程序中自动运行 Controller ?

c# - 在 Visual Studio 2017 中运行和调试 Powershell 模块