Asp.net-Mvc-3
ASP.Net MVC Razor 從 DateTime 屬性中刪除時間
我正在使用 Razor Views 開發一個 ASP.Net MVC 3 Web 應用程序。我有以下 ViewModel 傳遞給我的 Razor 視圖並迭代以顯示記錄列表。
視圖模型
public class ViewModelLocumEmpList { public IList<FormEmployment> LocumEmploymentList {get; set;} }看法
<table> <tr> <th>Employer</th> <th>Date</th> </tr> @foreach (var item in Model.LocumEmploymentList) { <tr> <td>@item.employerName</td> <td>@item.startDate</td> </tr> } </table>我的問題是這條線
@Html.DisplayFor(modelItem => item.startDate)返回這樣的日期20/06/2012 00:00:00,我希望它刪除時間並僅顯示日期,即20/06/2012。
我試過添加
@Html.DisplayFor(modelItem => item.startDate.Value.ToShortDateString())和
DisplayFor(modelItem => item.startDate.HasValue ? item.startDate.Value.ToShortDateString(): "")但是,它們都在執行時返回以下錯誤消息
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.我在這裡查看了 Darin Dimitrov 的回答Converting DateTime format using razor
但是,我無權訪問 ViewModel 中的 startDate 屬性,我的 ViewModel 返回您可以在上面看到的 FormEmployment 對象的 IList。
如果有人對如何從日期時間屬性中刪除時間有任何想法,那麼我將不勝感激。
謝謝。
另外,我的 startDate 屬性是 Nullable。
更新
根據 PinnyM 的回答,我添加了一個部分類(見下文)來放置
startDate 屬性上的屬性。
public partial class FormEmployment { [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")] public Nullable<System.DateTime> startDate { get; set; } }但是,我的 Razor View 仍然使用以下程式碼顯示20/06/2012 00:00:00
@Html.DisplayFor(modelItem => item.startDate)有任何想法嗎?
謝謝。
您可以使用
@item.startDate.Value.ToShortDateString()(為空值添加適當的驗證)
您可以在模型屬性上使用 DisplayFormat 屬性
startDate:[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")] public DateTime? startDate { get; set; }剛剛使用
DisplayFor(modelItem => item.startDate)另一種選擇是為格式創建一個只讀屬性:
public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }並使用
DisplayFor(modelItem => item.startDateFormatted)