Reputation: 4425
I´m trying to use TextBoxFor to display a input element to edit the time (Hour and Minutes) of a DateTime property.
In my model, the property is configured as follow:
public DateTime Hour { get; set; }
In my view:
@Html.TextBoxFor(model => model.Hora, "HH:mm", new { @class = "form-control" })
but always it display full date and time values, like:
11/25/2015 13:40:00
And I need only:
13:40
Upvotes: 1
Views: 4212
Reputation: 4425
I solved this problem using a auxiliary property in my class that maps DateTime to a string, already formatted.
In model:
private DateTime hour;
[Required]
public DateTime Hour //this is my mapped property
{
get
{
return hour;
}
set
{
hour = value;
//update unmapped property
hourString = value.ToString("HH:mm");
}
}
private string hourString;
[NotMapped]
public string HourString {
get
{
return hourString;
}
set
{
hour = new DateTime(hour.Year, hour.Month, hour.Day, Convert.ToInt16(value.Substring(0, 2)), Convert.ToInt16(value.Substring(3, 2)), 0);
}
}
Upvotes: 0
Reputation: 89
You can also use EditorFor instead of TextBoxFor and use data annotations in your model or viewModel, like this:
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
public DateTime Hour { get; set; }
And then in your view you use:
@Html.EditorFor(model => model.Hour, new { @class = "form-control" })
You can offcourse use the format you want for the string. In the link below you will find a complete reference:
https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Upvotes: 2
Reputation: 748
I've been using the jQuery.DateTimePicker with relative success.
In your view:
@Html.TextBoxFor(model => model.Hora, new { @class = "form-control" })
<script>
jQuery('#Hora').datetimepicker({
datepicker:false,
format:'H:i'
});
</script>
Upvotes: 0