arame3333
arame3333

Reputation: 10213

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?

Upvotes: 30

Views: 24931

Answers (4)

user3645143
user3645143

Reputation: 23

I ran across this problem when dealing with an old service that requires empty strings. I created an extension method:

public static string GetValueOrDefault(this string str)
        {
            return str ?? String.Empty;
        }

So you can use this when you want to make sure any strings that are null become empty

yourString1.GetValueOrDefault();
yourString2.GetValueOrDefault();

Upvotes: 1

Anders
Anders

Reputation: 754

An alternative solution to using attributes on each model property, as described in the accepted answer, is using a custom model binder, see string.empty converted to null when passing JSON object to MVC Controller

Upvotes: 1

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

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...

Upvotes: 62

djdd87
djdd87

Reputation: 68506

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

Upvotes: 2

Related Questions