使用DisplayFormat时,日期未在View中格式化

Cel*_*dor 2 c# asp.net-mvc razor asp.net-mvc-4

我有一个Student带有格式化属性DateTime?类型的示例类,只显示日期为dd/MM/yyyy.代码段如下:

public partial class Student
{
    // ...
    public DateTime? Date { get; set; }
}

[MetadataType(typeof(StudentMetaData))]
public partial class Student
{
}

public class StudentMetaData
{
    // ...
    [DisplayFormat(
        DataFormatString = "{0:dd/MM/yyyy}", 
        ApplyFormatInEditMode=true, 
        NullDisplayText="Date's not provided")]
    public DateTime? Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我将所有收集的学生List<Student>作为模型发送到视图并阅读记录,但该Date属性未按我的要求格式化.此外,当缺少特定字段中的日期时,它不提供文本.我还需要设置其他属性吗?这是视图中的代码:

@using MvcDbContext.Models
@model List<Student>
@{
    ViewBag.Title = "List of Students";
}
<h2>List of Students</h2>
<table>
    @foreach (Student student in Model)
    {
        <tr>
            <td>
                @student.StudentName
            </td>
            <td>
                @student.Gender
            </td>
            <td>
                @student.Date
            </td>
        </tr>
    }
</table>
Run Code Online (Sandbox Code Playgroud)

这是输出:

Adam     Male    07/05/2012 00:00:00  <- Date's not been formatted
Alex     Female  09/11/2014 00:00:00
Angela   Female  24/12/2011 00:00:00
Chris    Male                         <- here's supposed to be info "Date's not provided"
Clint    Male                         <- here's supposed to be info "Date's not provided"
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 6

如果你这样输出你基本上正在ToString()对值进行输出.而是使用Html助手:

@Html.DisplayFor(m => student.Date)
Run Code Online (Sandbox Code Playgroud)