0

I have a view which is used for "Create" and "Update" a database model. The database model has a property which is a DateTime? (nullable). Now I am trying to use this nullable datetime in an ASP.NET Core MVC view which looks like the following:

@Html.TextBoxFor(model => model.MyNullableDate,"{0:dd.MM.yyyy}", new { placeholder = "dd.MM.yyyy", @class = "form-control form-control-sm", type = "date" })

This works very well for the "Create" process. If a date is set, it is written correctly into the database. But now I want to update the already existing database value model.MyNullableDate.

I read the value from the database and pass the value again to the view. The property MyNullableDate is set correctly and I saw in the debugger that the correct date is written into it.

But in the view, nothing is shown... it's only an empty textbox without the passed in value of MyNullableDate.

The property looks like this:

    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
    [DataType(DataType.Date)]
    public DateTime? MyNullableDate{ get; set; }

What am I doing wrong? How can I show the value of MyNullableDate in the TextBoxFor?

1
  • 1
    Why is the placeholder format (mm/dd/yyyy) different from the one used in DataFormatString (dd.MM.yyyy)? Also, you've probably meant MM instead of mm Commented Mar 14, 2020 at 10:18

1 Answer 1

2

This is related to the date format rather than the nullability.

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

The displayed date format will differ from the actual value — the displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.

When I passed the format as below, the date displayed :)

@Html.TextBoxFor(
    expression: model => model.MyNullableDate, 
    format: "{0:yyyy-MM-dd}", 
    htmlAttributes: new
    {
        placeholder = "dd.MM.yyyy", 
        @class = "form-control form-control-sm", 
        type = "date"
    })
Sign up to request clarification or add additional context in comments.

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.