I used to receive empty string when there was no value:
[HttpPost] public ActionResult Add(string text) { // text is "" when there's no value provided by user }
But now I'm passing a model
[HttpPost] public ActionResult Add(SomeModel Model) { // model.Text is null when there's no value provided by user }
So I have to use the ?? ""
operator.
Why is this happening?
If you were to use s , it would actually have a value of null , because it holds absolute nothing. An empty string, however, is a value - it is a string of no characters. Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all.
You can use the DisplayFormat
attribute on the property of your model class:
[DisplayFormat(ConvertEmptyStringToNull = false)]
The default model binding will create a new SomeModel for you. The default value for the string type is null since it's a reference type, so it's being set to null.
Is this a use case for the string.IsNullOrEmpty() method?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With