当我为我的项目激活NRT时,如果您不在ASP.NET参数中传递变量值,则在模型绑定中遇到意外的行为。
public IActionResult MyAction(string testString)
{
// I assume there will be a non-null string and work with it,
// but I get NullReferenceException, because in fact
// for 'testString' I get null instead of String.Empty.
string trimmedString = testString.Trim();
// other code....
return View();
}怎么处理呢?
一种解决方案是使所有控制器操作中的所有字符串都为空,以避免欺骗自己和编译器。也许这是.NET模型绑定中的错误行为。
发布于 2022-07-08 02:24:09
您可以配置ConvertEmptyStringToNull来指定字符串类型的哪个属性可以是empty而不是null。
在这里,我创建了一个具有字符串类型的两个属性的类,一个属性具有[DisplayFormat(ConvertEmptyStringToNull = false)]属性,另一个属性没有
public class TestModel
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }
public string Age { get; set; }
}现在,我不传递URl参数中的任何值。您可以看到它们之间的区别:一个是empty,另一个是null。

https://stackoverflow.com/questions/72894531
复制相似问题