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?
5 Answers
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.