Formatting Date in ASP.NET MVC

I am having a little trouble figuring out how to format a date in my view. In my application, I have an Edit button. Once clicked on, the text box becomes editable with the date value. However, it is also showing me the time, which I don't want to see. How can I fix that?

Application

The Problem with the Application

The code in my Model Class:

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

The code in my View class:

<td class="Planned_Date">
    <span>@Html.DisplayFor(x=>item.Planned_Date)</span>
    @Html.TextBoxFor(x => item.Planned_Date)
</td>

The onClick():

  $("body").on("click", "#tblCustomers .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            $(this).hide();
        });

1 answer

  • answered 2018-10-11 19:08 Jack

    You need to edit your DataAnnotation on your model.

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    

    Add in the ApplyInEditMode property:

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}"), ApplyFormatInEditMode = true)]
    

    This will make the DataFormartString be applied to textboxes generated with EditorFor, or other editors. From this MSDN article,

    The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)

    Then, instead of declaring the input element in your view and setting the value from the model, you should update your view to use the Razor helper, Html.EditorFor. Refer to the Microsoft API for more information.

    <td class="Planned_Date">
        <span>@Html.DisplayFor(x=>item.Planned_Date)</span>
        @Html.EditorFor(x=>item.Planned_Date)  
    </td>
    

    You may have to adjust the example code to fit your situation (for example, adding classes or styles). Your JavaScript should still work.

    Note: The DisplayFormat DataAnnotation does not apply to inputs generated with Html.TextboxFor. It only applies to textboxes (or other editors) generated with Html.EditorFor and Razor Display helpers.