我有一个有两个约会的模特,我按照建议" 08/07/2013 08:00:00"和CurrentFocusDate" 08/07/2013 00:00:00"然而某些地方出现了问题,因为在页面中它们呈现的方式不同(请参阅下面的输出)任何人都知道为什么两个alsmot相同的属性会以不同的方式呈现?
模型
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)被切换。
答案 0 :(得分: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; }