我正在尝试将ID参数从一个视图传递到一个控制器,该控制器位于选中行上可用的click delete链接上。
简化视图布局
@using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { @class = "floating-labels" }))
{
@Html.AntiForgeryToken()
Delete
}JavaScript
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '@Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}控制器
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}但在点击删除链接时,我得到下面的错误,代码没有命中控制器操作。

我不知道我犯了什么错误...
发布于 2021-02-25 00:39:12
这是我在本地测试的实现,它正在工作。
ScheduleController类:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}发送post请求的页面:
@Html.AntiForgeryToken()
Delete
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}页面除了呈现html什么也不做,javascript处理实际的Ajax post。我认为您在请求中缺少的是验证令牌。
发布于 2021-02-19 03:11:12
读取错误请求很可能是正确发送的,并且存在500响应中提到的内部服务器错误,因此请检查控制器内部的代码
发布于 2021-02-19 03:13:40
尝试这样做,你正在访问c#代码上的javascript变量,而你不能这样做。如果正确,请标记为答案。
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '@Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}https://stackoverflow.com/questions/66228847
复制相似问题