Reputation: 396
When I activated NRT for my project, I encountered unexpected behavior in ASP.NET model binding, if you don't pass a variable value in the URL parameters.
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();
}
How to deal with it?
One solution is to make all string in all controller action nullable so as not to deceive yourself and the compiler. Perhaps this is the wrong behavior in the .NET model binding.
Upvotes: 0
Views: 132
Reputation: 9973
You can configure ConvertEmptyStringToNull
to specify which property of type string can be empty
instead of null
.
Here i create a class with two properties of type string, One with [DisplayFormat(ConvertEmptyStringToNull = false)]
attribute and o
ne without
public class TestModel
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }
public string Age { get; set; }
}
Now i don't pass any value in the URl parameter. You can see the difference between them: One is empty
and the other is null
Upvotes: 1