我有一个控制器,它有一个用于我的ajax请求的方法
$(document).on('click', '#btnSave', function (e) {
var array = {
some data
};
$.ajax({
url: window.location.origin + "/Page/ManageEmployee/Index/DataInsert",
type: "POST",
data: array,
success: function (response) {
var result = $(response).find('#body').html();
console.log(response);
$('#body').html(response);
},
error: function (xhr, status, error_m) {
alert(status + error_m);
}
});
});
这是我的ajax代码,我有三个ajax代码,它们都是相同的ajax请求方式,区别仅在于url。
对于操作名称删除
url: window.location.origin + "/Page/ManageEmployee/Index/Delete"
对于操作名称 Insert_Something
url:window.location.origin +“/Page/ManageEmployee/Index/Insert_Something”
控制器中的数据插入操作名称不起作用或出现错误
url:window.location.origin +“/Page/ManageEmployee/Index/DataInsert”
这是我项目中控制器的代码
我在不运行和执行时的方法上放置了调试器 它没有在DataInsert方法中跳转的程序或系统,因为 有一个ajax错误:
“加载资源失败:服务器响应状态为500 ()"
[HttpPost]
public ActionResult Delete(int index)
{
//this method run
}
[HttpPost]
public ActionResult Insert_Something(ModelClass data)
{
//this method run
}
[HttpPost]
public ActionResult DataInsert(ModelClass data)
{
//this method doesn't run
}
问题或我的问题是:
我如何修复在控制器中请求 post 方法时出现的错误,或者似乎是什么问题,因为其他 ajax 请求有效,但带有 url 的 ajax: DataInsert 不起作用
补充: 我刚开始使用 ASP.NET MVC,所以我的代码结构或我的工作方式对其他人来说可能很奇怪,只是通过依赖互联网上的帖子、yt 和互联网上的一些免费资源来学习这个框架。如果您可以建议或提供一些技巧来使我的结构更好或最佳实践,我可以更改以改进我的代码。
我刚开始使用 ASP.NET MVC,所以我的代码结构或工作方式 事情对其他人来说可能很奇怪,只需通过以下方式学习这个框架 依靠互联网上的帖子,YT和一些免费资源 互联网。如果您可以提供建议或提示来使我 结构更好或者我可以改变最佳实践来改进我的代码。
根据您共享的代码片段和您的路由定义,很明显,您的ajax URL不正确。您配置路由的方式会生成无效的 URL 以到达 API 控制器端点。
索取型号:
public class ModelClass
{
public int Id { get; set; }
public string Name { get; set; }
}
控制器:
假设您有以下 API 控制器:
[Route("api/[controller]")]
[ApiController]
public class ManageEmployeeController : ControllerBase
{
[HttpPost]
[Route("Insert_Something")]
public async Task<IActionResult> Insert_Something(ModelClass searchModel)
{
return Ok(searchModel);
}
}
Ajax 请求格式:
为了向上述控制器提交请求,您应该按如下方式装饰您的ajax请求:
$(document).on('click', '#btnSave', function (e) {
const array = { Id: 1, Name: "Test Name" };
var data = JSON.stringify(array);
$.ajax({
url: '/Api/ManageEmployee/Insert_Something',
type: 'POST',
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
},
error: function (e) {
}
});
});
输出: