ASP.Net Formato de pantalla MVC


En mi modelo tengo las siguientes anotaciones de datos en una de mis propiedades

[Required(ErrorMessage = "*")]
[DisplayFormat(DataFormatString = "{0:d}")]
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }

La anotación requerida funciona muy bien, agregué las otras 2 para intentar eliminar el tiempo. Se enlaza a una entrada en la vista usando

<%=Html.TextBoxFor(m => m.Birthdate, new { @class = "middle-input" })%>

Sin embargo, cada vez que se carga la vista, todavía obtengo el tiempo que aparece en el cuadro de entrada. ¿Hay alguna manera de eliminar esto usando DataAnnotations?

Author: Mathieu, 2010-01-04

3 answers

El atributo [DisplayFormat] solo se usa en EditorFor/DisplayFor, y no en las api HTML sin procesar como TextBoxFor.

 84
Author: Brad Wilson,
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-01-05 07:56:14

Como Brad dijo, no funciona para TextBoxFor, pero también deberá recordar agregar el ApplyFormatInEditMode si desea que funcione para EditorFor.

[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )]
public System.DateTime DateCreated { get; set; }

Luego use

@Html.EditorFor(model => model.DateCreated)
 28
Author: Paul Johnson,
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
2012-04-30 09:36:00

Mi problema fue establecer algunos atributos html (jquery-datepicker), por lo que EditorFor no era una opción para mí.

Implementando un ayudante personalizado-methode solucionó mi problema:

ModelClass con Propiedad DateTime:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime CustomDate{ get; set; }

Ver con modelClass como Modelo:

@Html.TextBoxWithFormatFor(m => m.CustomDate, new Dictionary<string, object> { { "class", "datepicker" } })

Helper-Metodo en la clase helper estática:

public static class HtmlHelperExtension {
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.TextBox(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName), string.Format(metadata.DisplayFormatString, metadata.Model), htmlAttributes);
    }
}
 7
Author: Tobias,
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
2014-02-27 14:14:46