2017-01-03 5 views
2

Ich habe eine Tabelle in meinem Rasierklingencode, die alle Elemente im Modell durchläuft und für jedes Element eine Tabellenzeile erstellt. Ich versuche herauszufinden, wie das Datum in MM/TT/JJJJ anstelle des Standardformats "MM/TT/JJJJ HH: MM: SS" formatiert wird.Formatieren von Daten in MVC 5 Razor

<table class="table-condensed"> 
    <thead> 
     <tr> 
      <th>Company</th> 
      <th>Contract No</th> 
      <th>Description</th> 
      <th>Expires</th> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach (var item in Model) 
     { 
      <tr> 
       <td>@Html.ActionLink(@item.CompanyName, "ViewContract", new { contractID = @item.ID }) </td> 
       <td width="200">@item.ContractNumber</td> 
       <td>@item.Description</td> 
       <td>@item.ExpireDate</td> 
      </tr> 
      } 
    </tbody>  
</table> 

Ich habe @ item.ExpireDate.ToString versucht ("MM/tt /"), aber es wirft eine Fehlermeldung, dass .ToString kein Argument.

+0

Ist ExpireDate ein Nullable-Datetime? – Brandon

+0

Ja. Außerdem benutze ich das MVCPagedList NuGet-Paket, das erfordert, dass Ihr Modell als PagedList übergeben wird. Deshalb kann ich keinen HTML-Helper verwenden. – Snicklefritz

+0

Ich hoffe, der Link: http: //stackoverflow.com/questions/4679352/converting- datetime-Format-Using-Rasiermesser hilft – shreesha

Antwort

1

Ich benutze das PagedList NuGet-Paket, das die Html-Helfer Anrufe ein wenig anders macht. Ich konnte das Datum formatieren, indem ich das Datumsformat im Datenmodellkonstruktor und dann den Anzeigehelfer anwendete.

im Datenmodell:

[DisplayFormat(DataFormatString = "{0: MM/dd/yyyy}")] 
public Nullable<System.DateTime> ExpireDate { get; set; } 

Im Rasierer:

<table class="table-condensed"> 
    <thead> 
     <tr> 
      <th>Company</th> 
      <th>Contract No</th> 
      <th>Description</th> 
      <th>Expires</th> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach (var item in Model) 
     { 
      <tr> 
       <td>@Html.ActionLink(@item.CompanyName, "ViewContract", new { contractID = @item.ID }) </td> 
       <td width="200">@item.ContractNumber</td> 
       <td>@item.Description</td> 
       <td>@Html.DisplayFor(modelItem => item.ExpireDate)<td> 
      </tr> 
      } 
    </tbody>  </table> 
4

Wenn Sie C# 6 Funktionen verwenden Sie ein Null bedingten verwenden können.

@(item.ExpireDate?.ToString("MM/dd/yyyy"))