如何使用ExtJS AJAX 调用在Web API中传递[FromBody]参数?

rm5edbpk  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(130)

我是新的ASP.NET核心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 AJAX 调用:

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

nsc4cvqm

nsc4cvqm1#

您没有通过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接受String或Object):

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 () {

        }
    });

相关问题