在ASP.NET Core 2.1中,我基本上注意到与此问题相反的情况:string.empty converted to null when passing JSON object to MVC Controller
当我将JSON
对象发送回具有空字符串属性的控制器时,它们不再自动转换为null
。
例如,使用此JS对象:
var person = {firstName:"", lastName:""};
$http.post("/app/index", person)
.then(function (response) {
// Success
}, function (error) {
// Failure
})
当绑定到控制器中的模型时,具有空字符串的属性将保留为空字符串:
//
// POST: /App
[HttpPost]
public async Task<ActionResult> Index([FromBody] AppFormDTO data)
{
....
}
将对象保存到数据库时,我更希望使用null
值而不是一堆空字符串。
他们是否更改了DefaultModelBinder
中的ASP.NET Core 2.1
?如果是这样,如何将其更改回MVC5中的状态-string.empty
已自动转换为null
?
更新,以添加我的AppFormDTO
模型,以供参考:
public class AppFormDTO
{
public string firstName{ get; set; }
public string lastName{ get; set; }
}
答案 0 :(得分:0)
仔细检查json对象的属性是否为null而不是空字符串...
答案 1 :(得分:0)
将其添加到您的PERSON模型中以获取名字/姓氏:
[DisplayFormat(ConvertEmptyStringToNull = false)]
... the model values
答案 2 :(得分:0)
在ASP.NET Core的source code之后
ƒ () {
sessionStorage.setItem('mf_start', '1');
activateMouseflow();
}
默认情况下,该行为设置为空字符串为null。
如果您输入的 if (bindingContext.ModelType == typeof(string))
{
// Already have a string. No further conversion required but handle ConvertEmptyStringToNull.
if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && string.IsNullOrWhiteSpace(value))
{
model = null;
}
else
{
model = value;
}
}
不正确,请重新检查模型AppFormDTO
。