7

I am trying to populate @Html.EditorFor helper. I have created a view model with the below property

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

and my helper is set up as below (a)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought, new { @type = "date" })

I have also tried (b)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought.Value.Date)

Using the above format (a) nothing is displayed. Using the above format (b) 12/05/2014 00:00:00 is displayed in textbox format.

I am trying to achieve a datepicker format without a time displayed

I have reviewed several other questions but cant see what i've done different.

When I look in my database, the value is save as 2014-05-12 and when I am saving the value the EditorFor helper generates the required input facility

questions reviewed

first second third....the list goes on

EDIT just opened the console in chrome dev tools and so this message

The specified value "12/05/14" does not conform to the required format, "yyyy-MM-dd"

I thought DisplayFormat(DataFormatString = "{0:dd/MM/yy}" was defining how to display my date?

Community
  • 1
  • 1
tony09uk
  • 2,841
  • 9
  • 45
  • 71
  • what is the extra `@type` for? in `@Html.EditorFor(model => model.YearBought, new { @type = "date" })` you can't specify htmlattributes if you use EditorFor so just curious – JamieD77 Oct 20 '15 at 21:44
  • @type date was a last ditch attempt to make it work, no other logic than that im afraid :( – tony09uk Oct 20 '15 at 21:54
  • Related: https://stackoverflow.com/questions/15943797/display-a-formatted-date-in-an-editorfor – vapcguy Oct 17 '18 at 20:59

4 Answers4

22

You need to use the ISO format when using type="date"

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

This will display the date in the browsers culture.

Note there is no need to add @type = "date". The EditorFor() method will add that because of the DataType attribute. Note also that type="date" is only supported in Chrome (FireFox and IE will just generate a normal textbox)

If you do want to display the format dd/MM/yyyy in a standard textbox then you can use

@Html.TextBoxFor(m => m.YearBought, "{0:dd/MM/yyyy}")
  • 2
    When I use same syntax in Editor for then it does not work @Html.EditorFor(m => m.YearBought, "{0:dd/MM/yyyy}") – Ashish Shukla May 06 '17 at 13:57
  • @AshishShukla, Because `EditorFor()` does not support that syntax. All you need is `@Html.TextBoxFor(m => m.YearBought)` - the `EditorFor() method respects values in the `DataType` and `DisplayFormat` attributes –  May 06 '17 at 22:49
  • To use `@Html.EditorFor()` you have to specify the format as `yyyy-MM-dd`, not like how it's shown in that `TextBoxFor`, above. Like it did Ashish, it might confuse some people into thinking you can use that format for `EditorFor` - you're right, you can't. But just doing `@Html.EditorFor(m => m.YearBought)` is definitely not enough, even with the model attributes. See my answer: https://stackoverflow.com/questions/33247295/show-only-the-date-in-html-editorfor-helper/52861439#52861439 – vapcguy Oct 17 '18 at 18:38
3

As it says in Stephen's answer, you have to make your formats match between the tags in your model to what is shown in the View, and it should be of the yyyy-MM-dd (ISO) format, regardless of how you actually want to display the date:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

// .... your namespace .... your class....

[DisplayName("Year Bought")]
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

And he's right, because we have [DataType(DataType.Date)], we don't need @type = date in our HtmlAttributes on the View.

Where my answer differs from his is how to actually apply the value from the Model to the control on the View. Since YearBought is a Nullable<DateTime>, we have to set it with its value a certain way, using .Value:

@Html.EditorFor(model => model.YearBought, 
    new { htmlAttributes = new { @class = "form-control datepicker", 
    @Value = Model.YearBought.Value.Date.ToString("yyyy-MM-dd") } })

Paying close attention to set the .ToString("yyyy-MM-dd"). It's not going to display in the box like that, though - at least for me - probably because my U.S. Regional settings on my computer take over and display it as MM/dd/yyyy regardless. This might confuse some, but it's better to just "do" and not worry about it.

If YearBought was just a straight DateTime instead of a DateTime?, it would be without the .Value:

@Html.EditorFor(model => model.YearBought, 
    new { htmlAttributes = new { @class = "form-control datepicker", 
    @Value = Model.YearBought != null ? 
    Model.YearBought.Value.Date.ToString("yyyy-MM-dd") : null } })
vapcguy
  • 7,097
  • 1
  • 56
  • 52
  • 1
    You NEVER set the `value` attribute when using `HtmlHelper` methods (unless you are trying to screw up model binding). –  Oct 17 '18 at 20:55
  • @StephenMuecke My model binding was already screwed up, because it wasn't working without this. Doing what I did above was the only thing I was able to do to get it to work. I posted this because I imagine it could happen to someone else, as well. – vapcguy Oct 17 '18 at 20:57
  • The you have something else causing it. All the `HtmlHelper` methods that generate form controls correctly set the `value` attribute by first reading it from `ModelState`, then the `ViewDataDictionary` and finally from the actual model value. –  Oct 17 '18 at 21:03
  • @StephenMuecke Don't think so. I have a ViewModel I was using that looks just like above. `myViewModel.startdt = DateTime.Now;` Passed it to my view with a `return View("MyView", myViewModel);` and had `using @model TestSite.ViewModels.MyViewModel` at the top. All my `EditorFor()` boxes were fine and posting from my model after a form postback, but the `EditorFor()` ones I was filling with dates were just "mm/dd/yyyy" if not setting a `@Value`. I'm not the only answer to ever say to use that, by the way: https://stackoverflow.com/questions/15943797/display-a-formatted-date-in-an-editorfor – vapcguy Oct 17 '18 at 21:08
  • Another wrong answer from a mvc beginner who does not know what they are doing or how the `HtmlHelper` methods work (without seeing your code, all I can do is guess that you are trying to change the value in your controller after a value has been added to `ModelState`) –  Oct 17 '18 at 21:13
  • @StephenMuecke What I'm doing has to be fairly common & I don't think I'm a novice-tho maybe not as adv as you. As I said, it was a postback onto a form. I set an empty model w/some prefilled properties (not the Start Date, but Created By, Created Date, etc.) in my Controller `Index()`, which does a `return View(myViewModel);`. Click a Save button after I upload a file-launches `Upload()` that reads properties & sets `myViewModel.startdt = DateTime.Now;` then it does `return View("Index", myViewModel);` to update the original model with my new values. As I said, only the dates have issues. – vapcguy Oct 17 '18 at 21:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182047/discussion-between-stephen-muecke-and-vapcguy). –  Oct 17 '18 at 21:30
0

I would make your view model's YearBought property a String for the easiest manipulation. The server can format the date, it can do the parsing on postback, and you can still use the DataType.Date data annotation for jQuery validation. This also ensures that the display value will be exactly what you want prior to being submitted to the view.

ps2goat
  • 8,067
  • 1
  • 35
  • 68
0

Alternative to the HTML type attribute, you can use an EditorTemplate in MVC to put the markup, CSS, and JS needed to render a custom editor for a known C# datatype like DateTime.

Here is a walkthrough for creating a custom 'EditorTemplate' in MVC (although not for a Date data type, but concept is the same)

Bishoy
  • 3,915
  • 29
  • 37