15

Razor ビューを使用して ASP.Net MVC 3 Web アプリケーションを開発しています。次の ViewModel を Razor View に渡し、反復してレコードのリストを表示します。

ビューモデル

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.

ここでダリン・ディミトロフの答えを見てきましたConverting DateTime format using razor

ただし、ViewModel の startDate プロパティにアクセスできません。ViewModel は、上記の FormEmployment オブジェクトの IList を返します。

日付と時刻のプロパティから時刻を削除する方法について誰かがアイデアを持っている場合は、非常に感謝しています。

ありがとう。

また、私の startDate プロパティは Nullable です。

アップデート

PinnyM の回答に基づいて、startDate プロパティに [DisplayFormat] 属性を配置する部分クラス (以下を参照) を追加しました。

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)

何か案は?

ありがとう。

4

3 に答える 3

35

使用できます @item.startDate.Value.ToShortDateString()(null値の適切な検証を追加)

于 2012-06-20T14:51:13.010 に答える
9

startDateモデルプロパティで DisplayFormat 属性を使用できます。

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }

ただの使い方DisplayFor(modelItem => item.startDate)

もう 1 つのオプションは、書式設定のためだけに読み取り専用プロパティを作成することです。

public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }

そして使うDisplayFor(modelItem => item.startDateFormatted)

于 2012-06-20T14:53:02.440 に答える