Use Separate Date Time

Asked

Viewed 80 times

2

I have a Datahora field and wanted to use it separately, that is, a single field in the database called Datahora of the datetime type, and manipulate this field with two editorfor where I save the date of one editorfor and the time of another editorfor in the same field of the database:

View:

<div class="form-group">
     @Html.LabelFor(model => model.DataHora, "Liberar encomenda as", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.EditorFor(model => model.DataHora, new { htmlAttributes = new { @class = "form-control" } }) Horas
     </div>
</div>
<div class="form-group">
     @Html.LabelFor(model => model.DataHora, "Liberar encomenda dia", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.EditorFor(model => model.DataHora, new { htmlAttributes = new { @class = "form-control" } })
     </div>
</div>

Class:

 public DateTime DataHora { get; set; }
  • Are you using a Persistence layer? If yes could put the class in your question, there is a way that you do not need to do much if it is that, depending even if it is without ORM also gives! Tell me how you save this information, post also your controller?

1 answer

2


If you necessarily want to use a database field, you will need a Viewmodel to consolidate date and time.

SeuModel.cs

public DateTime DataHora { get; set; }

SeuViewModel.cs

[DataType(DataType.Date)]
public DateTime Data { get; set; }
[DataType(DataType.Time)]
public TimeSpan Hora { get; set; }

View

<div class="form-group">
     @Html.LabelFor(model => model.Hora, "Liberar encomenda as", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.EditorFor(model => model.Hora, new { htmlAttributes = new { @class = "form-control" } }) Horas
     </div>
</div>
<div class="form-group">
     @Html.LabelFor(model => model.Data, "Liberar encomenda dia", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.EditorFor(model => model.Data, new { htmlAttributes = new { @class = "form-control" } })
     </div>
</div>

Controller

model.DataHora = viewModel.Data + viewModel.Hora;

Or even, you can define your Model already with the separate fields, there does not even need the Viewmodel, nor the logic of Controller above.

  • 1

    Separate in Model it will not have to have two fields in the bank

  • In this case @gypsy, your suggestion would be with the "Seuviewmodel.CS" would be a new class? I just didn’t understand this part...

  • That’s right. You create a class that is not linked to the database, but is used by View and Controller.

Browser other questions tagged

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