2013-08-06 22 views
0

我有一個有兩個日期的模型,我同時通過建議的「08/07/2013 08:00:00」和CurrentFocusDate「08/07/2013 00:00:00」,但是某處會出現錯誤,因爲它們在頁面中呈現的方式不同(請參閱下面的輸出)任何人都有一個想法,爲什麼兩個alsmot相同的屬性會呈現不同的渲染?Werid MVC日期問題

模型

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

出於好奇,如果從模型中刪除'HiddenInput'屬性會怎麼樣?我從來沒有親自使用過這個屬性,並且根據我是否想顯示值來指定'EditorFor'或'HiddenFor'。 – asymptoticFault

+0

裝修是否存在與否我無所謂。它實際上意味着呈現器的編輯器隱藏了輸入類型。 – Cookie

回答

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; } 
+0

似乎並不是這樣。如果我將它們都更改爲使用編輯器,我仍然會得到同樣的問題,那麼其中一個使用美國格式,另一個使用英國版本 – Cookie

+0

請確保已正確放置並命名模板:'〜/ Views/Shared/EditorTemplates/HiddenInput.cshtml' 。你是否也使用'[DisplayFormat]'屬性在視圖模型上裝飾Date屬性,如我的答案中所示?通過在其中放置一些容易識別的文本來驗證自定義編輯器模板實際上正在被使用。 –

+0

我改變它爲編輯器而不是隱藏輸入,並重命名該字段,似乎修復它。 – Cookie