Data Displayfor display formatting

Asked

Viewed 1,515 times

6

I have a field in the database, Date Time, and wanted to display on screen to the user, but in separate fields, being Date and Time.

First displays the Date

@Html.DisplayFor(modelItem => item.DataHora)

Second displays the Hour

@Html.DisplayFor(modelItem => item.DataHora)

I tried to format using the code below, but it didn’t work...

@Html.DisplayFor(modelItem => item.DataHora, {0:dd/MM/yyyy})

Dirt?

  • I prefer to use a view model and treat it in different properties. Example: public class Mymodel { public Datetime Datahora { get; set; } public string Data { get { Return Datahora.Toshortdatestring(); } } public string Time { get { Return Datatime.Toshorttimestring(); } } }

2 answers

6


Html.DisplayFor() does not serve for date and time separation as you want. The method meets well only for the integral use of variable information.

Use, instead of this:

@item.DataHora.ToString("dd/MM/yyyy")

and

@item.DataHora.ToString("HH:mm")
  • I take @Html.Displayfor(...) and put only @item.DataHora.Tostring... ?

  • 1

    Thanks again. It worked right here

  • 1

    Exactly. The DisplayFor has several utilities, but only with variables in its integrality.

0

I prefer to treat this in view model, example:

    public class MyModel
    {
        public DateTime? DataHora { get; set; }

        public string Data
        {
            get { return DataHora?.ToShortDateString(); }
        }

        public string Hora { get { return DataHora?.ToShortTimeString(); } }
    }

Browser other questions tagged

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