ajax - 如何使用 ExtJS AJAX 调用在 Web API 中传递 [FromBody] 参数?
问题描述
我是 ASP.NET Core Web API 的新手,我尝试通过ExtJS
AJAX 调用传递 [FromData],但它不起作用。
控制器方法:
这个方法我需要通过ExtJS
ajax调用来调用:
[HttpPost]
[Route("api/values/AddEmployee")]
public int AddEmployee([FromBody] Employee employee)
{
return objemployee.AddEmployee(employee);
}
员工模型:
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Department { get; set; }
public string City { get; set; }
}
ExtJS
阿贾克斯调用:
Ext.Ajax.request({
url: "http://localhost:1452/api/values/AddEmployee",
async: false,
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': '*/*' },
jsonData: {
employee: {
EmployeeId: 0,
Name: empName,
Gender: "Male",
Department: empDep,
City: empCity
}
},
success: function (data) {
me.down('#grdCaseList').getStore().reload();
},
failure: function () {
}
});
但是这个 AJAX 调用不起作用,我的代码有什么错误吗?
解决方案
您没有通过jsonData
参数传递有效的 JSON。您需要序列化您的 JSON 对象以正确格式化请求。尝试类似:
var employee = {
EmployeeId: 0,
Name: empName,
Gender: "Male",
Department: empDep,
City: empCity
};
Ext.Ajax.request({
url: "http://localhost:1452/api/values/AddEmployee",
async: false,
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': '*/*' },
jsonData: Ext.JSON.encode(employee),
success: function (data) {
me.down('#grdCaseList').getStore().reload();
},
failure: function () {
}
});
如果您想直接传递对象,那么您可以尝试(jsonData 采用字符串或对象):
Ext.Ajax.request({
url: "http://localhost:1452/api/values/AddEmployee",
async: false,
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': '*/*' },
jsonData: {
"EmployeeId": 0,
"Name": empName,
"Gender": "Male",
"Department": empDep,
"City": empCity
},
success: function (data) {
me.down('#grdCaseList').getStore().reload();
},
failure: function () {
}
});
推荐阅读
- java - 为什么在 java 中的“加入”线程开始之前 join() 方法之前的行不打印?
- matlab - 在 MATLAB 中计算 ANN 的误报率(逻辑错误)
- maven - Maven Flyway 执行插件
- java - 计算器逻辑错误
- encryption - 我可以从加密的 RAR 文件中提取的最小字节数是多少?如何提取它并使用 CRC32 进行验证
- javascript - 在测试中调用一个 Promise 在 NodeJS 中得到错误 400
- go - 无法分配给地图中的结构字段
- iis - 显示 Windows Server IIS 欢迎页面的 ASP.NET 网站
- raku - Perl 6 中嵌套列表的赋值
- regex - Python正则表达式非贪婪匹配