Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get null instead of empty string when receiving POST request in from Razor View?

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?

like image 460
Alex Avatar asked Sep 04 '10 09:09

Alex


People also ask

Why use null instead of empty string?

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.

Does Isnull check for empty string?

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.

What does empty string NOT NULL mean?

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.

Is empty string nil?

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.


2 Answers

You can use the DisplayFormat attribute on the property of your model class:

[DisplayFormat(ConvertEmptyStringToNull = false)] 
like image 60
Michael Jubb Avatar answered Sep 21 '22 04:09

Michael Jubb


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?

like image 32
hackerhasid Avatar answered Sep 22 '22 04:09

hackerhasid