0

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
  • 3
    What do you want the result to be? Commented Jul 1, 2009 at 8:19

5 Answers 5

2

Not sure about asp, but how about:

if (string.IsNullOrEmpty(text_from_textbox))
{
   date = DateTime.MinValue;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.