How to remove temporary part from DateTime variable in MVC

In my opinion, I have a date field (which is used for jQuery Date Picker),

@if (Model != null) { if (Model.SubmitStartDate == DateTime.MinValue) { Model.SubmitStartDate = null; } @Html.TextBoxFor(m => m.SubmitStartDate , new { @Id = "SubmitStartDate", @readonly = "readonly", @Value = @Model.SubmitStartDate}) } 

In my model, I have:

 [Required(ErrorMessage = "Please select a start date")] [DisplayFormat(DataFormatString = "{0:d}")] public DateTime? SubmitStartDate { get; set; } 

However, in the user interface, I get 10/07/2013 00:00:00 on boot, how can I remove some of the time from this. I also need a date in the format "dd-mm-yy" . Is it possible to achieve?

UPDATE

I edited my code in accordance with the answers, and I processed it according to the requirement, however, I had a problem.

When I use @Html.EditorFor() , the readonly property will no longer work. I also tried using DisplayFor , but that doesnโ€™t make sense, since I used it for a Date Select J-request. Is there a way to make this field read-only?

Updated Code:

 @if (Model != null) { if (Model.SubmitStartDate == DateTime.MinValue) { Model.SubmitStartDate = null; } @Html.EditorFor(m => m.SubmitStartDate , new { type = "date", @Id = "SubmitStartDate", @readonly = "readonly", @Value = @Model.SubmitStartDate}) } 
+6
source share
2 answers

You are using the @Html.TextBoxFor() , which will ignore your DisplayFormat attribute. Change it to @Html.EditorFor() and your DisplayFormat will be applied.

And to get your format:

 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yy}")] public DateTime? SubmitStartDate { get; set; } 
+15
source

This is how I usually format the data annotation to work in both chrome and IE.

 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime StartDate { get; set; } @Html.EditorFor(m => m.StartDate, new { type = "date" }) 
+1
source

Source: https://habr.com/ru/post/949024/


All Articles