asp.net-mvc ASP.Net MVC 显示格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2001756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.Net MVC DisplayFormat
提问by Gavin
In my model I have the following DataAnnotations on one of my properties
在我的模型中,我的属性之一具有以下 DataAnnotations
[Required(ErrorMessage = "*")]
[DisplayFormat(DataFormatString = "{0:d}")]
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
The required annotation works great, I added the other 2 to try and remove the time. It gets bound to an input in the view using
所需的注释效果很好,我添加了其他 2 个以尝试删除时间。它使用绑定到视图中的输入
<%=Html.TextBoxFor(m => m.Birthdate, new { @class = "middle-input" })%>
However whenever the view loads I still get the time appearing in the input box. Is there anyway to remove this using DataAnnotations?
但是,每当视图加载时,我仍然会在输入框中显示时间。有没有办法使用 DataAnnotations 删除它?
回答by Brad Wilson
The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor.
[DisplayFormat] 属性仅用于 EditorFor/DisplayFor,而不用于 TextBoxFor 等原始 HTML API。
回答by Paul Johnson
As Brad said it dosn't work for TextBoxFor but you'll also need to remember to add the ApplyFormatInEditMode if you want it to work for EditorFor.
正如 Brad 所说,它不适用于 TextBoxFor,但如果您希望它适用于 EditorFor,您还需要记住添加 ApplyFormatInEditMode。
[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )]
public System.DateTime DateCreated { get; set; }
Then use
然后使用
@Html.EditorFor(model => model.DateCreated)
回答by Tobias
My problem was to set some html attributes (jquery-datepicker), so EditorFor was no option for me.
我的问题是设置一些 html 属性(jquery-datepicker),所以 EditorFor 对我来说没有选择。
Implementing a custom helper-methode solved my problem:
实现自定义辅助方法解决了我的问题:
ModelClass with DateTime-Property:
具有日期时间属性的模型类:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime CustomDate{ get; set; }
View with ModelClass as Model:
以 ModelClass 作为模型查看:
@Html.TextBoxWithFormatFor(m => m.CustomDate, new Dictionary<string, object> { { "class", "datepicker" } })
Helper-Methode in static helper class:
静态助手类中的 Helper-Methode:
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);
}
}

