Html.HiddenFor在ASP.NET中错误地格式化DateTime

我正在用C#编写一个ASP.NET MVC3应用程序, Html.HiddenFor我的视图中调用Html.HiddenFor会以不同方式呈现DateTime (如果我要调用Html.DisplayFor ,则会错误地)。

从中获取值的模型确实有一个DisplayFormat装饰器,这似乎适用于Html.DisplayFor 。 有问题的财产写成:

 [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime MeetingStartDate { get; set; } 

视图显示使用:

  @Html.DisplayFor(model => model.MeetingStartDate) @Html.HiddenFor(model => model.MeetingStartDate) 

DisplayFor调用将日期显示为16/04/2012,但HiddenFor将其呈现为value="04/16/2012 00:00:00"

我已经尝试更改当前文化以设置DateTimeFormat但这没有任何效果。

目前的文化是en-GB,因此不应该打印en-US日期。

如果指定日期格式和html隐藏属性,则使用TextBoxFor的视图替代方法将起作用。

 @Html.TextBoxFor(model => model.CreatedDate, "{0:dd/MM/yyyy HH:mm:ss.fff}", htmlAttributes: new { @type = "hidden" }) 

如果要生成一个尊重所定义格式的隐藏字段,可以定义一个自定义编辑器模板来覆盖默认值( ~/Views/Shared/EditorTemplates/HiddenInput.cshtml ):

 @if (!ViewData.ModelMetadata.HideSurroundingHtml) { @ViewData.TemplateInfo.FormattedModelValue } @Html.Hidden("", ViewData.TemplateInfo.FormattedModelValue) 

现在用[HiddenInput]属性装饰你的模型属性:

 [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [HiddenInput(DisplayValue = false)] public DateTime MeetingStartDate { get; set; } 

在你看来:

 @Html.DisplayFor(model => model.MeetingStartDate) @Html.EditorFor(model => model.MeetingStartDate) 

这将使用正确的隐藏值格式:

  

或者你可以超越HiddenFor实现并重用TextBoxFor而手动设置type =“hidden”

像这样的东西:

 public static MvcHtmlString HiddenInputFor(this HtmlHelper html, Expression> expression, object htmlAttributes = null) { IDictionary htmlAttributesTmp = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (htmlAttributesTmp.ContainsKey("type")) { htmlAttributesTmp["type"] = "hidden"; } else { htmlAttributesTmp.Add("type", "hidden"); } return html.TextBoxFor(expression, htmlAttributesTmp); } 

在您的模型中,对于MeetingStartDate属性的Get函数,您可以返回格式化的DateTime吗?

DisplayFormat不适用于隐藏值,因为MVC正在隐藏字段中创建一个值,该值可以在表单提交操作期间从当前为该属性设置的数据中正确解析。

你有什么是MVC的预期行动。

如果你给id这样的问题不会发生

 <%= Html.TextBoxFor(model => Model.DiscountRate,new { @id = "DiscountRate", @Value=Model.DiscountRate})%> 
Interesting Posts