开发者

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

I try to format the datetime in the view.

<span class="tag">
   开发者_StackOverflow中文版     @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?


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.


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)


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜