tags:

views:

634

answers:

5

I have a not null sql datetime field and if my text box in the asp.net mvc app is blank, as it cannot convertt string.empty to datetime i get error. What is an elegant way of handling this situation?

+1  A: 

You have three options, depending on the requirements of the application:

  • Change the database to allow NULL's to be entered into the database. This would then require you to "special case" the logic so that rather than trying to blanket "Convert.ToDateTime" you check for string.Empty and pass DBNull.Value to the database instead.
  • Add some client-side validation to check for the textbox being empty and refuse to submit the form if it is. Accompany this with a validation check server-side that confirms the passed-in value is non-null (and also a valid date) and then fails the save and returns an error message to the user when a valid date is not present.
  • Put a default value (if possible) such as DateTime.Now into the database if the user fails to specify a value.
Rob
+2  A: 

Not sure about asp, but how about:

if (string.IsNullOrEmpty(text_from_textbox))
{
   date = DateTime.MinValue;
}
ChrisBD
+1  A: 

Don't try to save the data if it is not complete; show a validation error for the user and require a date to be filled in.

Fredrik Mörk
A: 

I absolutely agree with Fredrik. If you expect value in DB column, you must expect it in a model too. Use validation on client/server side before creating model from client's response.

Feryt
+1  A: 

Surely it's better to do

DateTime date;
if (!DateTime.TryParse(text_value, out date)) {
    date = DateTime.MinValue;
}

that way you handle empty strings and invalid dates

George