[英]Javascript passing null to MVC Controller
I have a Javascript code passing an object modeled exactly the same as my C# object CreateItemModel
. 我有一个Java代码,传递了一个与C#对象CreateItemModel
完全相同的对象。 However, problem is in my Controller code a property that was set in javascript as new String();
但是,问题是我的控制器代码中的一个属性在javascript中设置为new String();
gets deserialized to C# as null
. 被反序列化为C#为null
。
Javascript Code 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# Controller code C#控制器代码
[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. 我在这里期待一个string.empty
值,但我却得到了一个null
值。 I tried setting the _model.ItemDesc
to ''
""
new String()
in my Javascript code. 我尝试在Javascript代码中将_model.ItemDesc
设置为''
""
new String()
。 But always getting a null
value. 但是总是得到一个null
值。
Questions: 问题:
By default, the DefaultModelBinder
will interpret empty strings as null
. 默认情况下, DefaultModelBinder
会将空字符串解释为null
。 You can use the ConvertEmptyStringToNull
property of DisplayFormatAttribute
to have the property bind as an empty string. 您可以使用DisplayFormatAttribute
的ConvertEmptyStringToNull
属性将属性绑定为空字符串。
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ItemDesc { get; set; }
Try Changing the name item
to _model
尝试将名称item
更改为_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. contentType
和dataType
属性添加到您的ajax请求中。
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.