首页 > 解决方案 > 如何使用 ExtJS AJAX 调用在 Web API 中传递 [FromBody] 参数?

问题描述

我是 ASP.NET Core Web API 的新手,我尝试通过ExtJSAJAX 调用传递 [FromData],但它不起作用。

控制器方法:

这个方法我需要通过ExtJSajax调用来调用:

[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 调用不起作用,我的代码有什么错误吗?

标签: ajaxextjsasp.net-core-webapi

解决方案


您没有通过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 () {

        }
    });

推荐阅读