show only the date in @Html.EditorFor helper

后端 未结 4 1304
名媛妹妹
名媛妹妹 2020-12-04 00:33

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

[DataType(DataType.Date, ErrorMessage="D         


        
4条回答
  •  囚心锁ツ
    2020-12-04 01:09

    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, 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 } })
    

提交回复
热议问题