Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null FormData value converted to "null" string in .netcore 2.2 controller

Tags:

c#

ajax

.net-core

I'm trying to send an Ajax POST using FormData.

var data = new FormData();
data.append('id', 1);
data.append('description', null);

$.ajax({
    type: 'POST',
    url: '/TestController/UpdateDescription',
    data: data,
    contentType: false,
    processData: false,
    success: [...]
});

In the controller I have:

[HttpPost]
public JsonResult UpdateDescription(int id, string description)
{
    //description = "null", instead of null.
    bool isDescriptionNull = String.IsNullOrEmpty(description); //false!
}

I'm using the same code in a different .NET 4.7 project and this does not happens, and I get a null value for description.

What's happening here?

like image 360
Daniele Arrighi Avatar asked Nov 06 '22 16:11

Daniele Arrighi


1 Answers

Any value passed into data.append will be converted to a string. The only way to accomplish sending a null value is the send an empty string. i.e. data.append('description', ''); This will send a null value to the backend without stringifying it.

like image 110
Simone Anthony Avatar answered Nov 14 '22 22:11

Simone Anthony