qinking126
qinking126

Reputation: 11885

asp.net mvc3 how do you format the datetime in the view

I try to format the datetime in the view.

<span class="tag">
        @Html.DisplayFor(modelItem => item.PostDate.ToString("yyyy"))  
</span>

here's the error message I got.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

how do i fix it?

Upvotes: 3

Views: 3796

Answers (3)

TC MeTe Şeremet
TC MeTe Şeremet

Reputation: 1

@Html.DisplayFor(modelItem => item.PostDate).ToString().Substring(5,4)

So you can cut any part of your DateTime formatted field.

Upvotes: 0

Mansoor Gee
Mansoor Gee

Reputation: 1069

You can format your DateTime in the following way. It shows full date and time.

[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public DateTime PostDate { get; set; }

Then use it into View like this.

@Html.DisplayFor(model => model.PostDate)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

You decorate your view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:yyyy}", ApplyFormatInEditMode = true)]
public DateTime PostDate { get; set; }

and in your view you simply use the Html.DisplayFor method:

<span class="tag">
    @Html.DisplayFor(modelItem => item.PostDate)
</span>

or you could also use:

<span class="tag">
    @item.PostDate.ToString("yyyy")
</span>

but if you had this in many places the first approach is preferable because the format will be centralized in a single location.

Upvotes: 4

Related Questions