Reputation: 683
I have a Javascript code passing an object modeled exactly the same as my C# object
CreateItemModel
. However, problem is in my Controller code a property that was set in javascript as new String();
gets deserialized to C# as null
.
Javascript Code
$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc = new String();
$.ajax({
type: "POST",
url: 'CreateItem',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
console.log(msg);
},
error: function (msg) {
status = JSON.stringify(msg);
console.log(msg);
}
});
});
C# Controller code
[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc; //the property is null here
}
I was expecting a string.empty
value here but I am getting a null
value instead. I tried setting the _model.ItemDesc
to ''
""
new String()
in my Javascript code. But always getting a null
value.
Questions:
Upvotes: 0
Views: 883
Reputation:
By default, the DefaultModelBinder
will interpret empty strings as null
. You can use the ConvertEmptyStringToNull
property of DisplayFormatAttribute
to have the property bind as an empty string.
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ItemDesc { get; set; }
Upvotes: 4
Reputation: 1475
Try Changing the name item
to _model
[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel _model)
{
//breakpoint here
var test = _model.ItemDesc; //the property is null here
}
Also Add contentType
and dataType
properties to your ajax request.
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
Upvotes: 0