In the below code I am passing an empty value for "FirstName". When the Ajax POST request is made on the controller side the "FirstName" parameter value is coming as Null but if I pass any value the value is binded to the parameter. Only for the empty values, the value is showing as null in asp.Net core project
Javascript:
var dataVal = {};
dataVal["FirstName"] = "";
$.ajax({
type: "POST",
"url":url,
data:dataVal,
dataType: "json",
async: false,
success: function (m) {
if(m){
alert(m);
}
},
error: function(err){
}
});
Controller:
public IActionResult Home(string FirstName){
}
2
Answers
Do you want to receive
""
instead ofnull
in controller when ajax send request with the value ofFirstName
is""
?The explation about this is as follows:
This is simply because
MVC 2.0
defaults to initializing strings to null. To be more precise, if an empty string means has no value, So .NET sets the default value of its. And the default string (belonging to reference type) is null. So TheModelBinder
sets the properties to their default value if no value is provided in the request.refer to this link.
Attention: link provided above is about Asp.net MVC, There are some methods do not work in .Net Core. For example, Someone provided a method to change
bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
to receive""
in controller, But in asp.net core’s document:ConvertEmptyStringToNull
just has aget
method, So you can’t change it.Use the
[HttpPost]
attribute on the above action method and set the default value to string parameter. The below code for reference: