Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value of TextBox empty string instead of null

I may be out of date, but one principle I adhere to is avoid nulls as much as possible.

However what I have found is that for a strongly typed view in which the user inputs the properties of an object I want to save, if some fields are not entered they are assigned as null.

Then when you try to save the changes, the validation fails.

So rather than set each property to an empty string, how can I automatically set each TextBox on a form to default to an empty string rather than a null?

like image 852
arame3333 Avatar asked Aug 13 '10 08:08

arame3333


People also ask

What is the default value of string variable select one not defined NULL?

As you can see, for the integral value types, the default value is zero. The default value for the char type is the character equivalent of zero and false for the bool type. The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.

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.

Which is better empty string or NULL?

So it is better to use empty string for database as allowing NULL value forces the system to do extra work and does not give the data that you are looking for. However, NULL does not throw any exception when the count() function is executed.


2 Answers

You could put the following attribute on your string-properties in your model:

[DisplayFormat(ConvertEmptyStringToNull=false)] 

So whenever someone posts a form with empty text-fields, these will be an empty string instead of null...

like image 176
Yngve B-Nilsen Avatar answered Sep 21 '22 14:09

Yngve B-Nilsen


To be honest, I'd say your coding methodology is out of date and flawed. You should handle all possibilities, it's not hard. That's exactly what string.IsNullOrEmpty(value); is for.

I'm guessing your validation logic is something like:

if (value == string.Empty) { isValid = false; }  

So it doesn't handle the null values. You should replace that check so it also checks for nulls.

string value1 = null; string value2 = string.Empty;  string.IsNullOrEmpty(value1); // true string.IsNullOrEmpty(value2); // true 
like image 26
djdd87 Avatar answered Sep 24 '22 14:09

djdd87