Search code examples
ajaxpostactionresultasp.net-core-2.1

Unable to pass data from jQuery.ajax to .net Core 2.1 Actionresult


I want to send data to a .net core 2.1 Action method. I collect the data with jQuery and send it with Ajax. When inspecting the payload the object I want to send is there. But the method wont recivie it. All the values are Null.

The Code:

C#

public class Customer
{
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public string OrgNumber { get; set; }
    public string AdressLine1 { get; set; }
    public string AdressLine2 { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Image { get; set; }
    public int? StatusID { get; set; }
}

[HttpPost]
public async Task<IActionResult> Edit(Customer customer)
{

}
return View();

JavaScript

         var customerObject = {
                CustomerID: customerID,
                Name: customerName,
                OrgNumber: orgNumber,
                AdressLine1: adressOne,
                AdressLine2: adressTwo,
                ZipCode: zipCode,
                City: City,
                Country: Country,
                Image: customerImage,
                StatusID: statusId
            }

 var url = `@Url.Action("Edit")`;
            var postData = $.ajax({
                url: url,
                dataType: "json",
                contentType: "application/json;",
                data: { data: JSON.stringify(customerObject) },
                method: 'POST',
                async: true,
                crossDomain: true
            });

Payload from browser

data=%7B%22CustomerID%22%3A%2211%22%2C%22Name%22%3A%22Bambino+Kran%22%2C%22OrgNumber%22%3A%22456456131%22%2C%22AdressLine1%22%3A%22Lustikullagatan66%22%2C%22AdressLine2%22%3A%22%22%2C%22ZipCode%22%3A%2216578%22%2C%22City%22%3A%22H%C3%A4sselby%22%2C%22Country%22%3A%22%C3%96zbeckistan%22%2C%22Image%22%3A%22%22%2C%22StatusID%22%3A%221%22%7D

Payload deserialized:

{"CustomerID":"11","Name":"Bambino Kran","OrgNumber":"456456131","AdressLine1":"Lustikullagatan66","AdressLine2":"","ZipCode":"16578","City":"Hässelby","Country":"Özbeckistan","Image":"","StatusID":"1"}

enter image description here


Solution

  • Found this with a little bit of searching and solved it:

    jObject