Search code examples
ajaxextjsasp.net-core-webapi

How to pass [FromBody] parameter in Web API using ExtJS AJAX call?


I am new in ASP.NET Core Web API, I have tried to pass [FromData] through ExtJS AJAX call, but it's not working.

Controller Method:

This method I need to call through ExtJS ajax call:

[HttpPost]
[Route("api/values/AddEmployee")]
public int AddEmployee([FromBody] Employee employee)
{
        return objemployee.AddEmployee(employee);
}

Employee Model:

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 Call:

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

        }
    });

But this AJAX call is not working, is there any mistake in my code?


Solution

  • You are not passing valid JSON via the jsonData parameter. You need to serialise your JSON object in order to format the request correctly. Try something like:

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

    If you want to pass the object directly then you might try (jsonData takes a String or 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 () {
    
            }
        });