@Html.Editorfor Datetime property remove hh:mm:ss

Asked

Viewed 437 times

2

In my model have a field DateTime called Dating, I graduated with Attributes, but when I’m in view is filling in hh:mm:ss I just want the date 29/02/2016.

Model

[Column("sdt_DataReferencia")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name = "Referência 01/mm/aaaa")]
public DateTime DataReferencia { get; set; }

View:

<div class="form-group">
     @Html.LabelFor(model => model.Boletos.DataReferencia, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.EditorFor(model => model.Boletos.DataReferencia, new { htmlAttributes = new { @class = "form-control", @Value = Model.Boletos.DataReferencia }, })
    @Html.ValidationMessageFor(model => model.Boletos.DataReferencia, "", new { @class = "text-danger" })
</div>
</div>

1 answer

2


Visualization

Create in Views\Shared the directory DisplayTemplates.

Within it, create a View empty call DateTime.cs.

Within this View, put the following:

@model DateTime?

@if (Model.HasValue)
{
    @Convert.ToDateTime(Model).ToString("dd/MM/yyyy")
}

All the @Html.DisplayFor() will be displayed without the time.


Editing

Alternative 1: TexBoxFor

Use as follows:

@Html.TextBoxFor(model => model.Cliente.DataReferencia, "{0:dd/MM/yyyy}", new { @class = "form-control datepicker", placeholder = "Data de Referência" })

Alternative 2: Field Date

This uses the input Date browser native. Not always a good alternative because some inputKnown browsers are pretty bad.

Change this annotation:

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

To:

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

Just below, add:

[DataType(DataType.Date)]

No need to change the @Html.EditorFor.

  • the first is very interesting, but as I will use hh:mm:ss in some views then I will go to Alternative 1

  • 1

    I also had to take it out of Html.Edit @Value = Model.Validatededits, this also made the values wrong

Browser other questions tagged

You are not signed in. Login or sign up in order to post.