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

arame3333 picture arame3333 · Aug 13, 2010 · Viewed 22.3k times · Source

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?

Answer

Yngve B-Nilsen picture Yngve B-Nilsen · Aug 13, 2010

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