2016-06-30 19 views
0

Ich habe unten Einheit in einem MVC-Modell:Datumsformatierung in MVC Ansicht

[Display(Name = "Date Of Birth")] 
public DateTime? DateOfBirth { get; set; } 

und ich verwende es in einer Ansicht als:

<td title="@u.CreatedDate"> 
    @if (@u.DateOfBirth != null) 
    { 
     @u.DateOfBirth 
    } 
</td> 

Dieses arbeitet Stück Code, aber ich will um dieses Datum in TT/MM/JJJJ Format anzuzeigen.

Ich habe so etwas wie dies versucht:

1. string.Format("dd/MM/yyyy", u.DateOfBirth); 

2. [Display(Name = "Date Of Birth")] 
    [DisplayFormat (DataFormatString="dd/MM/yyyy")] 
    public DateTime? DateOfBirth { get; set; } 

Aber nichts funktioniert gut für mich. Bitte helfen

+0

'[Displayformat (Dataformatstring = "TT/MM/yyyy")]' funktioniert gut, wenn Sie '@ Html.DisplayFor (m => m.DateOfBirth)' verwenden. Alternativ verwenden Sie '@ u.DateOfBirth.ToString (" TT/MM/JJJJ ")' –

+0

Danke @StephenMuecke. Ich habe das schon versucht, aber es funktioniert auch nicht. Es zeigt einen Fehler, dass "Keine Überladungsmethode für ToString() 1 Argument" – Vipul

+0

Wenn seine Nullable, dann müssen Sie '@ u.DateOfBirth.Value.ToString (" TT/MM/JJJJ ")' –

Antwort

1

3 Optionen

@Html.DisplayFor(m => u.DateOfBirth) // assumes you have [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")] 

@String.Format("{0:dd/MM/yyyy}", u.DateOfBirth) 

@u.DateOfBirth.Value.ToString("dd/MM/yyyy") 

In den ersten zwei Fällen verwenden können, die Sie nicht brauchen die @if (@u.DateOfBirth != null) Check