Fecha solo desde TextBoxFor()


Estoy teniendo problemas para mostrar la única parte de fecha de una DateTime en un cuadro de texto usando TextBoxFor(expression, htmlAttributes).

El modelo se basa en Linq2Sql, el campo es un DateTime en SQL y en el modelo de entidad.

Error:

<%= Html.TextBoxFor(model => model.dtArrivalDate, String.Format("{0:dd/MM/yyyy}", Model.dtArrivalDate))%>

Este truco parece depreciarse, cualquier valor de cadena en el objeto HtmlAttribute se ignora.

Error:

[DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}" )]
public string dtArrivalDate { get; set; }

Me gustaría almacenar y mostrar solo la parte de fecha en la vista detalles/editar, sin la parte de" 00:00:00".

 254
Author: Brant Bobby, 2009-12-25

17 answers

[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

Entonces:

<%=Html.EditorFor(m => m.StartDate) %>
 225
Author: Kevin Craft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-23 09:26:06

MVC4 ha resuelto este problema agregando una nueva sobrecarga TextBoxFor, que toma un parámetro de formato de cadena. Ahora puedes simplemente hacer esto:

@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}")

También hay una sobrecarga que toma atributos html, por lo que puede configurar la clase CSS, los datepickers de cable, etc.:

@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}", new { @class="input-large" })
 338
Author: Ross McNab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-10 07:54:05
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>
 257
Author: Alexeyss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-11 13:33:21

O utilice los ayudantes sin tipo:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>
 48
Author: andersjanmyr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-29 07:57:37

Esto funcionó para mí.

@Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { size = "12", @class = "DOB", tabindex = 121 })
 22
Author: user5240713,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 19:59:43

No tenga miedo de usar HTML sin procesar.

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />
 12
Author: Tamas Czinege,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-26 08:28:38

También puede usar los atributos HTML 5 aplicando esta anotación de datos:

[DataType(DataType.Date)]

Pero el problema es que esto habilita un selector de fecha específico para navegadores HTML 5. Todavía necesita su propio selector de fecha para navegadores sin soporte, y luego tiene que asegurarse de que su selector de fecha no aparece además de un navegador (Modernizr puede hacer esto fácilmente), u ocultar el navegador si lo hace(complicado y no se cómo métodos confiables que vi eran).

Al final fui con Alex porque mi entorno actual no tiene Modernizr, pero si lo hiciera, lo habría utilizado para mostrar condicionalmente solo mi selector de datos si el navegador no admite uno ya.

 3
Author: AaronLS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 20:00:28

Para mí, necesitaba mantener el TextboxFor() porque usar EditorFor() cambia el tipo de entrada hasta la fecha. Que, en Chrome, agrega un selector de fecha incorporado, que arruinó el datepicker de jQuery que ya estaba usando. Por lo tanto, para continuar usando TextboxFor() Y solo mostrar la fecha, puede hacer esto:

<tr>
    <td class="Label">@Html.LabelFor(model => model.DeliveryDate)</td>
    @{
        string deliveryDate = Model.DeliveryDate.ToShortDateString();
    }
    <td>@Html.TextBoxFor(model => model.DeliveryDate, new { @Value = deliveryDate }) *</td>
    <td style="color: red;">@Html.ValidationMessageFor(model => model.DeliveryDate)</td>
</tr>
 2
Author: ScubaSteve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 20:01:43

El atributo DisplayFormat no funcionó para mí en ninguna de las dos formas durante la carga inicial. Creé un EditorTemplate en su lugar:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%=
    Html.TextBox("", Model.ToShortDateString(), new { @class = "date-range" }) %>
 1
Author: triskelion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-13 19:48:18

El Editor de plantillas solo funcionará con fines de visualización. Si usas el mismo editor (lo cual tiene sentido porque es un editor) y proporcionaste un valor como 31/01/2010, obtendrás un mensaje de error diciendo que el formato no es válido.

 1
Author: guerven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-16 02:04:58

Tenga en cuenta que la exhibición dependerá de la cultura. Y aunque en la mayoría de los casos todas las demás respuestas son correctas, no funcionó para mí. Problema de cultura también causará diferentes problemas con jQuery datepicker, si se adjunta.

Si desea forzar el formato escape / de la siguiente manera:

@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")

Si no se escapó para mí es mostrar 08-01-2010 vs espera 08/01/2010.

También si no se escapa jQuery datepicker seleccionará diferente defaultDate, en mi caso fue May 10, 2012.

 1
Author: CrnaStena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-01 12:26:27

/ / datimetime muestra en el datePicker es 11/24/2011 12: 00: 00 AM

/ / puede dividir esto por espacio y establecer el valor solo hasta la fecha

Script:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

Marcado:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

Espera que esto ayude..

 0
Author: coymax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-13 15:00:33

Seguro que puedes usar Html.EditorFor. Pero si quieres usar TextBoxFor y usar format desde el atributo DisplayFormat puedes usarlo de esta manera:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

O crear la siguiente extensión:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
    }
}
 0
Author: Yury Dzhantuganov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-15 22:45:49

Simplemente agregue al lado de su modelo.

[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }
 0
Author: arturas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 11:53:47

Cuando se utilizan ayudantes de etiqueta en ASP.NET Core, el formato necesita especificarse en formato ISO. Si no se especifica como tal, los datos de entrada enlazados no se mostrarán correctamente y se mostrarán como mm/dd/aaaa sin valor.

Modelo:

[Display(Name = "Hire")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? HireDate { get; set; }

Vista:

<input asp-for="Entity.HireDate" class="form-control" />

El formato también se puede especificar en la vista usando el atributo asp-format.

El HTML resultante se verá como sigue:

<input class="form-control" type="date" id="Entity_HireDate" 
    name="Entity.HireDate" value="2012-01-01">
 0
Author: Michael Emerick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 22:33:04

Yo uso Globalize así que trabajo con muchos formatos de fecha así que usa lo siguiente:

@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")

Esto ajustará automáticamente el formato de fecha a la configuración regional del navegador.

 0
Author: Liam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-26 07:54:48

Si está utilizando el selector de fecha Bootstrap, entonces puede agregar el atributo data_date_format como se muestra a continuación.

      @Html.TextBoxFor(m => m.StartDate, new { 
@id = "your-id", @class = "datepicker form-control input-datepicker", placeholder = "dd/mm/yyyy", data_date_format = "dd/mm/yyyy" 
})
 0
Author: uda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-28 06:59:36