到ASP的路由.asp.net Core MVC控制器从AJAX返回404



这应该是相当简单的,但我没有看到它。

通过AJAX调用将对象传递给控制器。对象是正确的。它没有找到路由器。

Javascript中的Ajax:

$('#employee_table tbody').on('click', '.editLink', function () {
var data = employee_table.row($(this).parents('tr')).data();
$.ajax({
type: 'POST',
data: data,
url: '/Employee',
contentType: 'application/json',
dataType: 'json'
});
});

控制器:

public class EmployeeController : Controller
{
private readonly IEmployeeService _iEmployeeService;
private readonly ICommentService _iCommentService;
public EmployeeController(IEmployeeService _iemployeeService, ICommentService _icommentService)
{
this._iEmployeeService = _iemployeeService;
_iCommentService = _icommentService;
}
public IActionResult Employee(object obj)
{
EmployeeDTO emp = (EmployeeDTO)obj;
EmployeeDetailViewModel employeeDetailViewModel = new(emp);
return View(employeeDetailViewModel);
}
}

控制台错误:

加载资源失败:服务器响应状态为404 ()Employee:1

如果我猜(不知道控制器是如何映射的,这只是一个猜测),我会说你需要调用url: '/Employee/Employee'。最简单的确认方法是用Swagger运行你的c#代码——它会告诉你方法的正确路径。

你的代码还有其他问题…首先,您正在从AJAX调用MVC控制器/方法-您将如何处理您将返回的HTML ?

正如@Felix所提到的,像这样更新您的代码:

$('#employee_table tbody').on('click', '.editLink', function () {
var data = employee_table.row($(this).parents('tr')).data();
$.ajax({
type: 'POST',
data: data,
url: '/Employee/Employee',
contentType: 'application/json',
dataType: 'json'
});
});

还要在Employee方法之上添加HttpPost。一定会成功的。

最新更新