0

我有一个有两个日期的模型,我将两者都传入 Proposed "08/07/2013 08:00:00" 和 CurrentFocusDate "08/07/2013 00:00:00" 但是页面中的某个地方出了问题它们以不同的方式呈现(见下面的输出) 任何人都知道为什么两个几乎相同的属性会以不同的方式呈现?

模型

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

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

    [HiddenInput(DisplayValue = true)]
    public string NavigationLink { get; set; }
}

看法

@Html.EditorFor(model => model.ProposedDateTime)
@Html.ValidationMessageFor(model => model.ProposedDateTime)

@Html.EditorFor(model => model.CurrentFocusDate)

@Html.HiddenFor(model => model.NavigationLink)

控制器

 public ActionResult AddNote(DateTime proposedEventDateTime, long productId, DateTime currentFocusDate, string navigationLink)
 { 
     var model = new AdminNoteViewModel
     {
         ProductId = productId,
         ProposedDateTime = proposedEventDateTime,
         CurrentFocusDate = currentFocusDate,
         NavigationLink = navigationLink
     };

     return View(model);
 }

这是渲染的源

<input data-val="true" data-val-date="The field ProposedDateTime must be a date." data-val-required="The ProposedDateTime field is required." id="ProposedDateTime" name="ProposedDateTime" type="hidden" value="07/08/2013 08:00:00" />
<span class="field-validation-valid" data-valmsg-for="ProposedDateTime" data-valmsg-replace="true"></span>

<input data-val="true" data-val-date="The field CurrentFocusDate must be a date." data-val-required="The CurrentFocusDate field is required." id="CurrentFocusDate" name="CurrentFocusDate" type="hidden" value="08/07/2013 00:00:00" />

<input id="NavigationLink" name="NavigationLink" type="hidden" value="Civica.DrugAdmin.UI.Models.AdminNoteViewModel" />

当我调试时,用于视图的模型的两个日期格式都正确,但是当它们在页面上呈现时,其中一个(currentFocusDate)会被切换。

4

1 回答 1

3

根据设计,HiddenFor帮助器(最终由 EditorFor 使用)在呈现其值时始终使用当前的文化格式。如果您想覆盖此行为,您可以编写自定义编辑器模板 ( ~/Views/Shared/EditorTemplates/HiddenInput.cshtml):

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

然后您将能够使用DisplayFormat属性指定格式并覆盖当前文化的格式:

[HiddenInput(DisplayValue = false)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime ProposedDateTime { get; set; }
于 2013-08-06T15:16:14.590 回答