Hexxed
Hexxed

Reputation: 683

Javascript passing null to MVC Controller

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:

  1. Why is this behavior occurring?
  2. How to get my expected value?

Upvotes: 0

Views: 883

Answers (2)

user3559349
user3559349

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

Roopak Puthenveettil
Roopak Puthenveettil

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

Related Questions