0

我有一个 Javascript 代码传递一个与我的 C# 对象完全相同的对象 CreateItemModel。但是,问题是在我的控制器代码中,一个在 javascript as 中设置的属性new String();被反序列化为 C# as null

Javascript代码

$('[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# 控制器代码

[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
   //breakpoint here 
   var test = item.ItemDesc; //the property is null here
}

我在这里期待一个string.empty价值,但我得到了一个null价值。我尝试在我的 Javascript 代码中设置_model.ItemDesc为。'' "" new String()但总是得到一个null价值。

问题:

  1. 为什么会出现这种行为?
  2. 如何获得我的期望值?
4

2 回答 2

4

默认情况下,DefaultModelBinder会将空字符串解释为null. 您可以使用 的ConvertEmptyStringToNull属性DisplayFormatAttribute将属性绑定为空字符串。

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ItemDesc { get; set; }
于 2018-11-09T06:32:44.233 回答
0

尝试将名称更改item_model

    [HttpPost]
    public async Task<JsonResult> CreateItemCallAsync(CreateItemModel _model)
    {
       //breakpoint here 
       var test = _model.ItemDesc; //the property is null here
    }

contentType还将和属性添加dataType到您的 ajax 请求中。

$.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
于 2018-11-09T06:26:19.493 回答