0

I'm messing about with the html5 date input field.

<input type="date" >

I noticed that when you clear the field the value is set to an empty string. So when you post this value to your backend (ASP.NET MVC) the model binder gives a "String was not recognized as a valid DateTime" instead of just setting it to null.

So I was wondering what the easiest way to tell the model binder that when the field type is DateTime an empty string should be parsed to null.

Model example:

public class MyModel
{
    public DateTime? MyDate { get; set; }
}

Ctrl example:

public void Post(MyModel model)
{
    ...
}

1 Answer 1

2

DateTime is a value type, it can't hold null. You can use Nullable<T> struct (DateTime? or Nullable<DateTime>) to hold null values.

public class MyModel
{
    public Nullable<DateTime> MyDate { get; set; }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Haha, woops. I just assumed since it's an object :). Hold on let me test with nullable.
This is one of many reasons to use view models. If your MyDate property on your database-persisted entity needs to be not null, you can still make the property on your view model nullable, and then just find some way to recover if it is null, when you try to set MyDate on the entity.
Okay just tested. DateTime? still generates an error.
@Snæbjørn, the error is due to MVC handling mapping of date type to DateTime in .Net, I am not an expert in MVC, but you can't hold null in a non-nullable DateTime. So my answer , actually answers half part of your question, I will leave it here, until you get some working new answer.

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.