Reputation: 11885
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
Reputation: 1
@Html.DisplayFor(modelItem => item.PostDate).ToString().Substring(5,4)
So you can cut any part of your DateTime
formatted field.
Upvotes: 0
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
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