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?
+1
A:
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
GenericTypeTea
2010-08-13 09:07:11
I can see my question isn't clear.I am looking for an answer to do with metadata or an extended template. This is a MVC question rather than a C# question.
arame3333
2010-08-13 09:11:38
Post some code in your question so we can see what you're tring to do.
GenericTypeTea
2010-08-13 09:22:51
I am not sure what code I can show you. I have some TextBoxes in a View, and if the user does not enter a value before submitting, they default to null. If the fields in the underlying model are NOT nullable, this causes the validation to fail.I have found an answer based on this question on SO;http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-customInstead of trimming I just set a null string to an empty string. I am happy with this answer, but maybe there is an easier one?
arame3333
2010-08-13 10:02:49
+1
A:
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...
Yngve B. Nilsen
2010-08-13 10:43:23