我已经在这里待了一个小时了,但我不知道我做错了什么。
我得到以下 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/