Html.EditorFor and custom format

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

Is it possible?

+6
c # asp.net-mvc razor
source share
2 answers

One solution I found for me was to add a strongly typed partial view (for System.DateTime ) and put it in the Views/Shared/EditorTemplates . The DateTime.cshtml file looks something like this:

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

This, however, will format all your DateTime fields.

More information can be found in this article.

+7
source share

Write a helper 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 your view:

 <%= Html.MyEditor(Model.YourDateTimeField) %> 
+2
source share

All Articles