6

I got a property in my model which is a DateTime . I would like to get an empty <input /> (instead of one containing '0001-01-01 00:00:00') if the property contains DateTime.MinValue.

Is that possible?

2 Answers 2

7

One solution I've found working for me was to add strongly typed partial view (for System.DateTime) and put it in Views/Shared/EditorTemplates directory. File DateTime.cshtml looks pretty much like this:

@model System.DateTime
@Html.TextBox("", Model == DateTime.MinValue ? "" : Model.ToShortDateString())

This will however format all your DateTime fields.

More information can be found in this article.

Sign up to request clarification or add additional context in comments.

Comments

2

Write an extension helper method:

public static class DateTimeHelper
{
    public static string MyEditor(this HtmlHelper helper, DateTime date)
    {
        if (date.Equals(DateTime.MinValue))
        {
            // return your an empty input: helper.TextBox ...
        }
        // return helper.EditorFor your datetime
    }
}

Then, from you view:

<%= Html.MyEditor(Model.YourDateTimeField) %>

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.