0

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?
0

2 Answers 2

4

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; }
Sign up to request clarification or add additional context in comments.

Comments

0

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",

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.